Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/sys-session-revoke-by-id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'@objectstack/plugin-auth': patch
'@objectstack/platform-objects': patch
---

fix(plugin-auth,platform-objects): Revoke Session on a `sys_session` row ends the session it names

Clause-②: no

- **The action.** The `sys_session` `revoke_session` row action (Setup → Sessions, Account → Active Sessions) posts the row's `id` as `sessionId` to a new plugin-auth route, `POST /api/v1/auth/sys-session/revoke`. The server resolves the session from the id. The session token stays `internal: true`: it is not served to the console or to any other client, and no request to or answer from this route carries it.
- **Who may revoke.** The session's owner: the route hands the request to better-auth's own `POST /api/v1/auth/revoke-session`, so that route's checks and its `user_revoked` record apply exactly as before. Another user's session: a platform administrator only (the ADR-0068 D2 standing every `/api/v1/auth/admin/*` mount judges). The session is ended in place with `revoke_reason: admin` (ADR-0069 D4), stays listed under the Revoked view, and its next request is unauthenticated.
- **Refusals.** An anonymous caller: `401 UNAUTHENTICATED`. A body without `sessionId`: `400 INVALID_REQUEST`. Every other caller, and an id that names no live session: `404 RESOURCE_NOT_FOUND`, one answer for every cause. A platform administrator whose own sign-in is held by the authentication policy: `403` with the policy's code.
- **Unchanged.** `POST /api/v1/auth/revoke-session`, "Sign out other devices", and every `sys_session` read path.
28 changes: 14 additions & 14 deletions content/docs/permissions/tenant-audit-census.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ are reported as `undecidable` rather than assumed either way.

The same holds twice over for the context. An options argument spelled as a
literal can be read; one spelled `options`, `{ ...opts }`, or handed through a
forwarding shim cannot, and **50 of the 231 sites are spelled that way**. A
forwarding shim cannot, and **50 of the 232 sites are spelled that way**. A
context resolved from an inline literal or a local `const` can be tested for
`isSystem`; one arriving from a helper call cannot.

Expand Down Expand Up @@ -187,10 +187,10 @@ reproduce them. Where it disagrees, it disagrees on the page:

| carried figure | where it survives | this census |
| :--- | :--- | ---: |
| 175 write call sites | quoted in the merged changeset | **231** |
| 175 write call sites | quoted in the merged changeset | **232** |
| 24 carrying no tenant context | quoted in the merged changeset | **2** provable and tenancy-enabled; **29** more whose options argument is unreadable |
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **156 of 231** decidable, **75** undecidable |
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 130 decidably elevated, 0 decidably not, 93 undecidable |
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **156 of 232** decidable, **76** undecidable |
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 131 decidably elevated, 0 decidably not, 93 undecidable |
| 141 and 132, two independent re-derivations | the card that filed this work | — |

**The differences are not reconciled, and deliberately so.** The old census's
Expand All @@ -207,11 +207,11 @@ would report a smaller number and would not say so.

The fourth row is the one worth flagging to anyone citing it. **The 135 / 77%
figure has no surviving corroboration anywhere in the tree.** This census reads
130 of 231 (56%) as decidably elevated, with 93 more whose elevation is a
131 of 232 (56%) as decidably elevated, with 93 more whose elevation is a
run-time fact — so the claim is neither confirmed nor refuted, and the honest
answer is that a static reading cannot settle it.

⇒ **Cite `2 / 231`, and say what it is**: the sites whose options argument was
⇒ **Cite `2 / 232`, and say what it is**: the sites whose options argument was
READ and holds no tenant context, against a decidably tenancy-enabled object.
That is the control's provable yield surface. ⛔ Do not cite it as "the sites
without tenant context" — **29 further sites** have an options argument this
Expand All @@ -223,31 +223,31 @@ cannot read, and they are neither in nor out.

| what | count |
| :--- | ---: |
| write call sites on the application surface | **231** |
| write call sites on the application surface | **232** |
| …whose object name is statically decidable | 156 |
| …whose object name is chosen at run time | 75 |
| …whose object name is chosen at run time | 76 |
| …against an object with tenancy ENABLED | 155 |
| …against an object that declares tenancy off | 1 |
| threading a tenant context | 173 |
| threading a tenant context | 174 |
| PROVABLY carrying none (options read, no context key) | **8** |
| …of those, against a decidably tenancy-enabled object | **2** |
| options argument UNREADABLE — may or may not carry one | 50 |
| …of those, against a decidably tenancy-enabled object | 29 |
| threading a decidably ELEVATED (`isSystem`) context | 130 |
| threading a decidably ELEVATED (`isSystem`) context | 131 |
| threading a context that is decidably NOT elevated | 0 |
| threading a context whose elevation is a run-time fact | 93 |

| how the instrument reached the site | count |
| :--- | ---: |
| receiver carried a readable engine type | 190 |
| receiver carried a readable engine type | 191 |
| receiver erased, placed by the object NAME | 31 |
| receiver erased, placed by an `object: string` PARAMETER | 5 |
| receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 |

| object name spelled inline | 107 |
| object name spelled through a `const` | 49 |
| object name is an `object: string` parameter | 7 |
| object name is some other run-time expression | 68 |
| object name is some other run-time expression | 69 |

### Subtractions the census could NOT defend — enforced

Expand Down Expand Up @@ -297,11 +297,11 @@ holds still. They are required to be HERE and to say WHEN they were true;
their values are not compared. The reasoning, and the measurement behind it,
are in `scripts/check-tenant-audit-census.mjs`.

Measured on 2026-10-20 at `1f2b0cb73`.
Measured on 2026-10-20 at `300e9d436`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 674 |
| tracked non-test sources scanned | 675 |
| engine-shaped types recognised | 80 |
| declared objects in the registry | 118 |
| same-named calls subtracted as non-engine | 166 |
Expand Down
13 changes: 7 additions & 6 deletions docs/audits/2026-08-tenant-audit-write-call-sites.counts.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution.

| Measure | Value |
|---|---:|
| Write call sites | 231 |
| Write call sites | 232 |
| Object name statically decidable | 156 |
| Object name chosen at run time | 75 |
| Object name chosen at run time | 76 |
| Against a tenancy-enabled object | 155 |
| Against an object declaring tenancy off | 1 |
| Threading a tenant context | 173 |
| Threading a tenant context | 174 |
| Provably carrying none | 8 |
| …and decidably tenancy-enabled | 2 |
| Options argument unreadable | 50 |
| …and decidably tenancy-enabled | 29 |
| Threading a decidably elevated context | 130 |
| Threading a decidably elevated context | 131 |
| Threading a decidably non-elevated context | 0 |
| Threading a context of undecidable elevation | 93 |

Expand Down Expand Up @@ -90,11 +90,11 @@ holds still. They are required to be HERE and to say WHEN they were true;
their values are not compared. The reasoning, and the measurement behind it,
are in `scripts/check-tenant-audit-census.mjs`.

Measured on 2026-10-20 at `1f2b0cb73`.
Measured on 2026-10-20 at `300e9d436`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 674 |
| tracked non-test sources scanned | 675 |
| engine-shaped types recognised | 80 |
| declared objects in the registry | 118 |
| same-named calls subtracted as non-engine | 166 |
Expand Down Expand Up @@ -158,6 +158,7 @@ Measured on 2026-10-20 at `1f2b0cb73`.
| `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `insert` | `sys_scim_connection_credential` | enabled | PROVABLY NONE | 1 |
| `packages/plugins/plugin-auth/src/session-tombstone.ts` | `update` | `objectName` | undecidable | options unreadable | 1 |
| `packages/plugins/plugin-auth/src/sso-client-secret.ts` | `update` | `sys_sso_provider` | disabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 |
| `packages/plugins/plugin-email/src/attachment-reclaim.ts` | `update` | `object` | undecidable | elevated | 1 |
| `packages/plugins/plugin-email/src/email-plugin.ts` | `insert` | `object` | undecidable | elevated | 1 |
| `packages/plugins/plugin-email/src/email-plugin.ts` | `update` | `object` | undecidable | elevated | 1 |
Expand Down
13 changes: 9 additions & 4 deletions packages/platform-objects/src/identity/sys-session.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,15 @@ export const SysSession = ObjectSchema.create({
mode: 'delete',
locations: ['list_item'],
type: 'api',
target: '/api/v1/auth/revoke-session',
// better-auth `revoke-session` keys off the session token, not the id.
recordIdParam: 'token',
recordIdField: 'token',
// Keyed on the row's `id` — every list row carries it — and resolved to
// the session SERVER-side by plugin-auth's `sys-session/revoke` door, so
// the `internal` token below is never sent to or from the console. That
// door admits the session's owner (better-auth's own `/revoke-session`)
// and, for another user's session, a platform administrator (ADR-0068
// D2). ⛔ Never key this action on `token`: no read path serves it, so a
// row can never supply it.
target: '/api/v1/auth/sys-session/revoke',
recordIdParam: 'sessionId',
confirmText: 'Revoke this session? The user will be signed out from that device.',
successMessage: 'Session revoked',
refreshAfter: true,
Expand Down
47 changes: 47 additions & 0 deletions packages/platform-objects/src/platform-objects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,53 @@ describe('@objectstack/platform-objects', () => {
expect(role.description).toContain('OS_PLATFORM_OWNER_EMAIL');
expect(role.description).toContain('`single`');
});

it('SysSession revoke_session identifies its session by the row id, resolved server-side', () => {
const revoke = (SysSession.actions ?? []).find((a) => a.name === 'revoke_session');
expect(revoke).toBeDefined();
expect(revoke?.type).toBe('api');
expect(revoke?.locations).toEqual(['list_item']);
expect(revoke?.target).toBe('/api/v1/auth/sys-session/revoke');
expect(revoke?.recordIdParam).toBe('sessionId');
// The row field that seeds `recordIdParam` defaults to `id` — the one
// column every list row carries.
expect(revoke?.recordIdField ?? 'id').toBe('id');
expect(SysSession.fields.id).toBeDefined();
});

it('SysSession keeps its session token internal: no read path serves it', () => {
const token = SysSession.fields.token as { internal?: unknown; hidden?: unknown; readonly?: unknown };
expect(token.internal).toBe(true);
expect(token.hidden).toBe(true);
expect(token.readonly).toBe(true);
});

it('no identity action identifies its record by a field the server never serves', () => {
// An action seeds `recordIdParam` from the ROW the console holds. An
// `internal` field is omitted from every read, so it can never be on that
// row, and an action keyed on one can never name its record.
const objects = [
SysAccount, SysApiKey, SysBusinessUnit, SysBusinessUnitMember, SysDeviceCode,
SysInvitation, SysJwks, SysMember, SysOauthAccessToken, SysOauthApplication,
SysOauthRefreshToken, SysOrganization, SysSession, SysSsoProvider, SysTeam,
SysTeamMember, SysTwoFactor, SysUser, SysUserPreference, SysVerification,
];
const offenders: string[] = [];
let seeded = 0;
for (const object of objects) {
for (const action of object.actions ?? []) {
if (!action.recordIdParam && !action.recordIdField) continue;
seeded += 1;
const field = action.recordIdField ?? 'id';
const declared = (object.fields as Record<string, { internal?: unknown } | undefined>)[field];
if (field !== 'id' && !declared) offenders.push(`${object.name}.${action.name}: '${field}' is not a field`);
if (declared?.internal === true) offenders.push(`${object.name}.${action.name}: '${field}' is internal`);
}
}
// Positive control: the sweep reaches real declarations.
expect(seeded).toBeGreaterThan(0);
expect(offenders).toEqual([]);
});
});

describe('data portability — derived, not declared (#3025 / #3543)', () => {
Expand Down
25 changes: 25 additions & 0 deletions packages/plugins/plugin-auth/src/auth-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import { MANAGED_EXTENSION_EDITABLE_FIELDS } from './managed-extension-fields.js
import { runSetInitialPassword } from './set-initial-password.js';
import { runRegisterSsoProviderFromForm, runRegisterSamlProviderFromForm, runRequestDomainVerification, runVerifyDomain } from './register-sso-provider.js';
import { runResendVerificationEmail } from './send-verification-email.js';
import { runSysSessionRevoke, sysSessionRevokeDepsFor } from './sys-session-revoke.js';
import { readJsonRequestBody } from './request-json-body.js';
import type { CounterStore } from './rate-limit-storage.js';
import { authIdentityManifest } from './manifest.js';
Expand Down Expand Up @@ -3550,6 +3551,30 @@ export class AuthPlugin implements Plugin {
}
});

// ────────────────────────────────────────────────────────────────────
// Revoke ONE session, named by its `sys_session.id` — the door behind the
// `sys_session` Revoke Session row action (Setup → Sessions, Account →
// Active Sessions). The server resolves the session from the id, so the
// session token never travels to or from the console. The owner lane
// re-dispatches to better-auth's own `/revoke-session`; another user's
// session is revocable by a platform administrator only (ADR-0068 D2
// judge). Same family as `sys-oauth-application/register` above: an
// object-scoped mount outside `/admin/`, because it admits the owner.
// See `sys-session-revoke.ts` for the lanes and refusals.
rawApp.post(`${basePath}/sys-session/revoke`, async (c: any) => {
try {
const { status, body } = await runSysSessionRevoke(
sysSessionRevokeDepsFor(this.authManager!, basePath),
c.req.raw,
);
return c.json(body, status as any);
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
ctx.logger.error('[AuthPlugin] sys-session/revoke failed', err);
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
}
});

// ────────────────────────────────────────────────────────────────────
// Self-service resend of the email-verification link. SHADOWS better-auth's
// native `/send-verification-email` (registered before the catch-all below).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,11 @@ describe('auth route ledger hygiene', () => {
'POST /api/v1/auth/organization/add-member',
'POST /api/v1/auth/set-initial-password',
'POST /api/v1/auth/sys-oauth-application/register',
// The fourteenth, on this pin's own terms: `auth-plugin.ts` mounts it
// itself (a `rawApp.post` on the `${basePath}/sys-session/revoke`
// template, ahead of the catch-all), and the `live.has(route)` loop
// below holds it to the same proof — better-auth serves no by-id revoke.
'POST /api/v1/auth/sys-session/revoke',
]);
for (const route of own) {
expect(live.has(route), `${route} should NOT come from better-auth`).toBe(false);
Expand Down
1 change: 1 addition & 0 deletions packages/plugins/plugin-auth/src/auth-route-ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
{ route: 'POST /api/v1/auth/admin/set-user-manager', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user set_user_manager action posts it directly; sets or clears sys_user.manager_id, which drives the approvals `manager` rung and the own_and_reports scope and had no product write surface at all (the ADR-0092 D2 managed-update whitelist is {name,image,locale}). Runs under a system context so it reaches the column BY CONTEXT, not by whitelist — no Tier-1 list moves and the column keeps readonly: true; platform-admin gated (ADR-0068), ADR-0057 / ADR-0092' },
{ route: 'POST /api/v1/auth/admin/unlock-user', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user unlock_user action posts it directly; clears a brute-force lockout (sys_user.locked_until / failed_login_count), a custom per-identity mechanism with no better-auth endpoint; platform-admin gated (ADR-0068), ADR-0069 D2' },
{ route: 'POST /api/v1/auth/sys-oauth-application/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application create action posts it directly; session-required self-service wrapper over better-auth /oauth2/create-client that splits the Console\'s newline-separated redirect-URL textarea into the redirect_uris array the vendor schema requires' },
{ route: 'POST /api/v1/auth/sys-session/revoke', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_session revoke_session row action posts it directly with the row id; the server resolves the session from the id, so the session token never travels to or from the console. The session owner is re-dispatched to better-auth /revoke-session; another user\'s session is revocable by a platform admin only (ADR-0068 D2), tombstoned with reason admin (ADR-0069 D4)' },
{ route: 'POST /api/v1/auth/organization/accept-invitation', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.invitations.accept', requires: 'organization' },
// #9941 — better-auth declares `addMember` with NO HTTP path (server-only
// `auth.api.addMember`; measured on the installed 1.7.1), so the catch-all
Expand Down
6 changes: 4 additions & 2 deletions packages/plugins/plugin-auth/src/session-tombstone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,10 @@ import { SystemObjectName } from '@objectstack/spec/system';
* the session. Recording `admin` for a user clicking "sign out my other
* devices" would not be a vague audit record, it would be a **wrong** one — it
* names an actor class that took no action, which is worse for an auditor than
* no record at all. `admin` therefore means exactly the two `/admin/*` routes,
* and `user_revoked` means the session's own owner did it.
* no record at all. `admin` therefore means exactly the two `/admin/*` routes
* — plus the administrator lane of `sys-session-revoke.ts`, which writes this
* ledger's `admin` value itself — and `user_revoked` means the session's own
* owner did it.
*/
export const INTERACTIVE_REVOKE_REASON: Readonly<Record<string, string>> = {
// Self-service — the session owner acting on their own sessions.
Expand Down
Loading
Loading