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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
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
36 changes: 36 additions & 0 deletions .changeset/dev-admin-seed-credential-gate.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
---
'@objectstack/plugin-auth': minor
'@objectstack/cli': patch
---

Fix: `objectstack dev` now seeds its dev admin on a database that has PEOPLE but no LOGIN

An app that declares `sys_user` rows in `defineStack({ data })` used to lose the
`objectstack dev` login permanently. The declarative seed is awaited inside
`AppPlugin.start()`, so it always landed before the dev-admin seed's own
`kernel:ready` hook; the seed's gate asked "does any human `sys_user` row
exist?" and skipped — on that boot and on every later one, because the rows
survive. The deployment ended up with no loginable account at all: people rows
present, `sys_account` empty, `POST /auth/sign-in/email` returning 401.

A seeded person is a directory row with no credential. It is not a login, and
the gate now says so: the seed acts while no account holds the configured seed
address and no local password login (`sys_account.provider_id = 'credential'`)
exists anywhere. "Never overwrites an existing account" is unchanged and now
covers federated accounts on that address too. A credential store that cannot be
read is its own verdict — the seed declines and says so, rather than minting a
known-credential admin into an environment it could not see.

The seed's own provisioning call is now admitted as what it is — the
deployment's own boot command provisioning its admin — instead of riding on the
audience gate's zero-human bootstrap bypass, which the app's people seed also
answers "populated". The public self-registration door is unchanged: nothing
outside the process can stage that declaration, it names one address, and it is
cleared as soon as the call returns.

`GET /api/v1/auth/bootstrap-status` now answers with the same bootstrap-window
question the admission gate asks, instead of counting `sys_user` rows with no
filter. On a database still carrying the legacy `usr_system` service row it used
to report `hasOwner: true` while the admission gate and plugin-security's
first-user detection both stood ready to admit and promote the first human — so
the console withheld a first-run setup flow the platform would have accepted.
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line numberDiff line numberDiff line change
Expand Up@@ -97,7 +97,7 @@ that silently does not happen.
| 8 | `explain()` may target a principal other than the caller | plugin-security | Get: no `manage_users` / delegated-admin check | `security-plugin.ts:3857` |
| 9 | Anonymous-deny treats the caller as authenticated | core | Get: passes the 401 seam with no `userId` | `anonymous-deny.ts:154` |
| 10 | Permission-set projection middleware skipped | plugin-security | Lose: projection of permission-set-derived columns | `permission-set-projection.ts:1015` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1296` |
| 11 | Session-resolution middleware skipped | plugin-auth | Get: no session lookup attempted | `auth-plugin.ts:1301` |
| 12 | Per-request performance timings disclosed | observability | Get: timing headers a normal caller cannot pull | `perf-timing.ts:474` |
| 13 | Permission-set **overlay discard** skips the tenant-admin assertion | plugin-security | Get: an overlay can be discarded with no authenticated tenant administrator | `permission-set-overlay-discard.ts:142` |
| 14 | MCP stdio bridge skips the object API-exposure gate | mcp | Get: the bridge reaches objects whose `apiEnabled` / `apiMethods` would refuse an external caller | `stdio-data-bridge.ts:246` |
Expand Down
15 changes: 9 additions & 6 deletions packages/cli/src/commands/dev.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,7 +139,7 @@ export default class Dev extends Command {
default: false,
}),
'seed-admin': Flags.boolean({
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime on an EMPTY DB, then promote it to platform admin. Default: on (idempotent — only acts on a zero-user DB, never overwrites an existing account). Disable with --no-seed-admin.',
description: 'Seed a known, loginable dev admin (admin@objectos.ai / admin123) in-process via the runtime when the database carries NO LOGIN yet, then promote it to platform admin. Default: on (idempotent — it acts only while no account holds the seed address and no local password login exists anywhere, never overwrites an existing account). Disable with --no-seed-admin.',
allowNo: true,
}),
'admin-email': Flags.string({
Expand DownExpand Up@@ -331,11 +331,14 @@ export default class Dev extends Command {
// loader off.
// ── Dev admin seeding (in-process) ──────────────────────────────
// Seeding is performed IN-PROCESS by the runtime
// (@objectstack/plugin-auth → maybeSeedDevAdmin) on an empty DB — no
// HTTP POST, no port, no readiness race. The CLI's only job is to pass
// the toggle + credentials through to the serve child via env.
// Default ON in dev; `--no-seed-admin` disables it. The seed is
// idempotent (empty-DB only) and never overwrites an existing account.
// (@objectstack/plugin-auth → maybeSeedDevAdmin) — no HTTP POST, no
// port, no readiness race. The CLI's only job is to pass the toggle +
// credentials through to the serve child via env. Default ON in dev;
// `--no-seed-admin` disables it. [#14157] The seed is idempotent and
// gated on the absence of a LOGIN (no account on the seed address, no
// local password login anywhere) rather than on an empty user table —
// an app that declares people in `defineStack({ data })` fills that
// table before the seed runs. It never overwrites an existing account.
const seedAdmin = flags['seed-admin'] ?? true;

// Resolve the database through the ONE shared resolution (#6469) —
Expand Down
135 changes: 127 additions & 8 deletions packages/plugins/plugin-auth/src/auth-manager.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,6 +18,7 @@ import {
isHumanUserRow,
resolveAudience,
AUDIENCE_CONFIG_ERROR,
type AudienceCreationClass,
type ResolvedAudience,
} from './audience-posture.js';
import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js';
Expand DownExpand Up@@ -1055,10 +1056,11 @@ export class AuthManager {

/**
* Result of the dev-only admin seed (set by `AuthPlugin.maybeSeedDevAdmin`
* when it provisions the well-known admin on an empty DB). The `serve`
* command reads this after boot to surface the credentials in the startup
* banner. Undefined when no seed ran (production, opt-out, or a DB that
* already had a user).
* when it provisions the well-known admin, or re-armed on a later boot while
* that account still carries the default password). The `serve` command
* reads this after boot to surface the credentials in the startup banner.
* Undefined when no seed ran (production, opt-out, or [#14157] a database
* that already carries a login).
*/
public devSeedResult?: { email: string; password: string };

Expand DownExpand Up@@ -1951,7 +1953,14 @@ export class AuthManager {
// `catch` read that refusal as "users exist" and the declared
// bypass never fired on a real deployment. `isBootstrapCreation`
// owns the answerable form — see its doc.
if (await this.isBootstrapCreation()) {
// [#14157] …and the deployment's own boot command provisioning its
// admin is the OTHER way through this door. It is not a
// self-registration and must not depend on a self-registration
// carve-out: an app that seeds people makes the bootstrap probe
// answer "populated" before the seed ever runs. Cheap synchronous
// check first, so the ticket path costs no I/O.
const signUpEmail = typeof ctx?.body?.email === 'string' ? ctx.body.email : undefined;
if (this.isOperatorProvisioning(signUpEmail) || (await this.isBootstrapCreation())) {
ctx.context.__osDisableSignUpOrig = ep.disableSignUp;
ep.disableSignUp = false;
}
Expand DownExpand Up@@ -3661,6 +3670,20 @@ export class AuthManager {

private static readonly OWNER_STAMP_STAGE_TTL_MS = 10 * 60 * 1000;

/**
* [#14157] Addresses the deployment's OWN boot command is provisioning right
* now — see {@link stageOperatorProvisioning} for why this exists and why it
* is not the bootstrap probe.
*/
private pendingOperatorProvisioning = new Map<string, { stagedAtMs: number }>();

/**
* Deliberately short. The window this covers is a single in-process
* `signUpEmail` call that the caller also clears in a `finally`; the TTL is
* only the floor under a caller killed between the two.
*/
private static readonly OPERATOR_PROVISIONING_STAGE_TTL_MS = 60 * 1000;

/**
* Page size of the bootstrap population probe ({@link isBootstrapCreation}).
* Matches the bound the dev-admin seed reads with, so the two ask the same
Expand DownExpand Up@@ -3747,10 +3770,17 @@ export class AuthManager {
// EXISTENCE.
if (data?.source?.action !== 'create-user') return undefined;
const audience = this.getAudience();
const creationClass = classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
const email = typeof data?.user?.email === 'string' ? (data.user.email as string) : undefined;
// [#14157] A creation the deployment's own boot command staged is the
// OPERATOR class — the vendor's `source.method` cannot carry that,
// because the seed reaches better-auth through the same `signUpEmail`
// API a person's sign-up does. See `stageOperatorProvisioning` for why
// this is a declared ticket and not a wider bootstrap probe.
const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email)
? 'operator'
: classifyCreationMethod(data?.source, {
enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(),
});
let isBootstrap = false;
let hasPendingInvitation = false;
if (creationClass === 'self-serve') {
Expand DownExpand Up@@ -4030,6 +4060,95 @@ export class AuthManager {
}
}

/**
* [#14157] Declare that the deployment's own boot command is provisioning
* this address right now, so its creation is judged as the **operator**
* class it actually is rather than as a self-registration.
*
* ## Why this exists instead of widening the bootstrap probe
*
* The dev-admin seed provisions through the real `signUpEmail` pipeline (it
* must: that is what produces a hashed credential and runs the sign-up
* hooks), and until now its admission rode on
* {@link isBootstrapCreation} — "zero HUMAN users". That is a **public
* self-registration carve-out**: it is what lets an unknown visitor's first
* sign-up through under `invite_only`. Its population predicate therefore
* has to keep counting humans, because the population it is protecting
* against is humans.
*
* The seed's precondition is a different question — "does a LOGIN exist?"
* (`dev-admin-seed-gate.ts`) — and #14157 is what happens when the two are
* conflated: an app that seeds people in `defineStack({ data })` makes the
* database non-zero-user before the seed runs, and the dev admin is never
* minted. Fixing only the seed's own gate does not help, because the
* admission still refuses: **measured**, with 13 seeded people and zero
* accounts, `api.signUpEmail` comes back `SELF_REGISTRATION_CLOSED` under
* the default `invite_only` posture.
*
* So the seed says what it *is* instead of inferring admission from a
* population it does not own. That is the same claim
* `walled-owner-operator-stamp.ts` already makes about this account —
* "provisioned by the deployment's own boot command with operator-known
* credentials" — and it moves no public door: nothing outside this process
* can stage a ticket, the only caller is hard-gated to
* `NODE_ENV==='development'`, the ticket names ONE address, the caller
* clears it in a `finally`, and anything that outlives that is pruned by
* {@link OPERATOR_PROVISIONING_STAGE_TTL_MS}.
*/
stageOperatorProvisioning(email: string): void {
this.prunePendingOperatorProvisioning();
this.pendingOperatorProvisioning.set(email.trim().toLowerCase(), { stagedAtMs: Date.now() });
}

/** [#14157] Drop the ticket staged by {@link stageOperatorProvisioning}. */
clearOperatorProvisioning(email: string): void {
this.pendingOperatorProvisioning.delete(email.trim().toLowerCase());
}

/**
* [#14157] Is this address being provisioned by the deployment's own boot
* command? A PEEK, not a consume: both admission seams (the `disableSignUp`
* bypass and `validateAudienceAdmission`) ask about the same single
* creation, so a one-shot read here would admit at the first seam and refuse
* at the second. The ticket's lifetime is bounded by its owner's `finally`
* and by the TTL instead.
*/
isOperatorProvisioning(email: unknown): boolean {
if (typeof email !== 'string' || email.trim() === '') return false;
this.prunePendingOperatorProvisioning();
return this.pendingOperatorProvisioning.has(email.trim().toLowerCase());
}

private prunePendingOperatorProvisioning(): void {
const cutoff = Date.now() - AuthManager.OPERATOR_PROVISIONING_STAGE_TTL_MS;
for (const [key, value] of this.pendingOperatorProvisioning) {
if (value.stagedAtMs < cutoff) this.pendingOperatorProvisioning.delete(key);
}
}

/**
* [#14157] The bootstrap window, as a PUBLIC read — "can a first-run owner
* still be created here?".
*
* `GET /auth/bootstrap-status` answers the console's first-run routing
* question, and it used to answer it by counting `sys_user` rows, which
* makes it the one call site that disagrees with the three
* {@link isHumanUserRow} consumers: on a database still carrying the legacy
* `usr_system` service row it reports an owner while the audience gate and
* plugin-security's first-user detection both say the first human is still
* ahead — i.e. the console withholds the setup flow that the platform is
* standing ready to admit and promote. Reading THIS method keeps the console
* from ever offering a first-run creation the admission gate would refuse,
* and from ever hiding one it would allow.
*
* Never throws; an unanswerable probe reads as "no window" — the same
* fail-closed direction the admission gate takes, and the same answer the
* route's own catch produced.
*/
async hasBootstrapWindow(): Promise<boolean> {
return this.isBootstrapCreation();
}

private stageSelfRegistrationGrant(email: string, setName: string): void {
this.prunePendingSelfRegistrationGrants();
this.pendingSelfRegistrationGrants.set(email.trim().toLowerCase(), {
Expand Down
Loading
Loading