What's new in Nexler
Fix: a callable value set in the database is no longer overwritten at startup
Fixed: core.SyncTasks replaced each core_tasks document on every start, so a callable changed in the database was reset to the value in code. Once a task has an entry, the stored callable now wins; code only sets it for a task with no entry yet. This means a later Callable: true in code (e.g. -callable) does not change an existing task, so change it in the database. Mongo core only. nexler update patches an existing app's core/tasks.go (and reports a copy it can't match instead of overwriting it).
Tags: update
Tasks addressable over HTTP; service callers acting for a user and an org; nexler update -opt-out
New: core_tasks records how to call each task: service, method, path, base_path and callable. openapi.Operation gains Task and Callable, generated routes set Task, openapi.Operations() lists the registered operations, and nexler create <route> -callable marks new methods as callable by another service (e.g. a workflow engine). Mongo core only.
New: a service-key caller may send X-Acting-Subject (written to the audit entry as acting_subject, read with auth.ActingSubject) and, on a -multitenant app, X-Org-Id. The org is honoured only for a service whose core_services record allows it (acts_for_orgs; core.ServiceActsForOrgs/SetServiceActsForOrgs); otherwise the request gets 403. New file middleware/service_caller.go.
Retrofit: four new nexler update checks bring an existing app up to date. They insert rather than regenerate, so a hand-extended openapi.go is kept: the Operation fields and Operations(); core/tasks.go (regenerated only when it still has its generated shape); Task on existing openapi.Register blocks; and the service-caller pieces. Fixed: nexler update -merge-service-auth and -multitenant failed to render middleware/auth.go (missing HasCoreDB/CoreDBAccessor/Multitenant template data).
Fixed: main.go called core.SyncTasks before routes.Register, but routes add their tasks to the registry inside Register. So on a real start core_tasks received nothing. The call now comes after routes.Register, and the new check main.go: core.SyncTasks after routes.Register moves it in existing apps. New: SyncTasks deletes this service's core_tasks entries for tasks it no longer registers, such as a renamed or removed route. It only touches entries carrying its own service name, and never runs when the registry is empty. Entries with no service (synced before the field existed) are left for a person to remove.
Fixed while rolling out to existing apps:
the Task retrofit now also handles compact openapi.Register blocks (Method: "GET", Path: "/x", … on one line);
the service-caller retrofit now handles an older serviceDoc without LastUsedAt;
and permission_kpass.go is no longer written into an app whose own middleware/task.go has no PermissionCheck hook (it did not compile there).
New: nexler update -opt-out admin-users,admin-services (and -opt-in) records, in a committed nexler.json, admin pieces an app removed on purpose. Before this, nexler update put handlers/admin/users, handlers/admin/services and core/users.go back every time. ensureAdminRoutes, ensureServiceAuth and -merge-service-auth all honour it.
Tags: task registry, auth, update
Fix: repeated nexler update duplicated Task fields
Fixed: on an app with compact openapi.Register blocks (Method: "GET", Path: "/x", Task: "…", … on one line), every nexler update after the first added Task again, and the app stopped compiling with duplicate field name Task in struct literal. The check now finds an existing Task anywhere in the block. An app already hit by it needs the second Task: "…", removed from each block once.
Tags: update
Task Registry (baseline) + nexler init tenant
New, baseline for every app: every generated route (including the Admin API) is now wired via middleware.RegisterTask(action, requireAuth, reqType, respType, pathParams...) instead of a bare handler or a direct RequireAuth wrap — see The Task Registry. It registers each route's contract into a new in-process task package, best-effort audit-logs every call via a new core.LogAudit (on a core-database app), and — via a new nil-by-default middleware.PermissionCheck hook — gives every protected route a real, shared authorization gate for the first time: nexler init kpass now wires it automatically to services/kpass.CheckAccess. A core-database app also gets core.SyncTasks, mirroring the registry into a new core_tasks table/collection at startup (reusing /openapi.json's own reflection via a newly-exported openapi.JSONSchema). nexler update backfills an older app via two new checks, ensureTaskRegistry and ensureKpassPermissionHook — deliberately does not rewrite already-generated routes' wiring, only new ones going forward.
New command: nexler init tenant adds a guarded tenantorg listing/delete admin API (GET /admin/tenants, DELETE /admin/tenants/{id}) for a hub (or similar) app to manage tenants — see nexler init tenant. Deliberately independent of core/ and of the existing -multitenant flag: a new opt-in tenant/tenant.go package holds free-form per-organization settings, scoped to list/delete only in this release. nexler init db provisions tenant_orgs conditional on that package existing on disk (SQL cores only — Mongo needs no provisioning).
Tags: auth, scaffolding, new command
kgate: resilient delivery, plus business logic moved into services/kgate/services/kpass
New: kgate/kgate.go's WebSocket loop gained structured log/slog logging (JSON, tagged component=kgate, never including an event's payload), a bounded 15s dial timeout, WebSocket ping/pong keepalive (5s/15s — tuned against a real kgate deployment's own idle-disconnect behavior), panic-safe dispatch (runSubscribeOnce/dispatchEvent), and permanent-vs-transient error handling (permanentError/permanentf/isPermanent — a payload that will never decode is acked once and logged loudly instead of resurfacing on every future reconnect). Publish's payload is now JSON-encoded on the wire (undone on receipt by the new unwrapPayload) and sends an Origin header alongside X-Client-Id. Existing apps pick all of this up via three new nexler update checks (ensureKgatePublishEncoding/ensureKgateResilientDelivery/ensureKgateWebhookDispatch), same anchor-based-patch-with-hand-rewrite-guard precedent as every earlier kgate retrofit.
Structural change: handleEvent's real implementation and Register's hardcoded startup Subscribe(ctx, "test") call — both business decisions that used to live inside kgate/kgate.go, a file nexler update patches over time — are now package-variable hooks (EventHandler/OnStartup) that a new one-time-written package, services/kgate/kgate.go, overrides via its own init(). kgate/kgate.go is now pure, permanently-stable infrastructure with nothing left to protect from a future patch — matching kpass/kpass.go's already-safe status. kpass gets the same treatment for consistency: nexler init kpass now also writes services/kpass/kpass.go (CheckAccess, wrapping kpass.Check/Allowed) — call that instead of kpass.Check directly from your handlers. A new ensureKgateServiceExtraction retrofit migrates an existing app automatically only if handleEvent is still untouched; a hand-customized handleEvent makes it error out instead, naming the exact manual migration steps — it never silently relocates real business logic. ensureKpassService backfills services/kpass for an app that ran init kpass before this existed.
Tags: kgate, kpass, scaffolding
nexler update is now best-effort; mongo/mongo.go anchor and Filter retrofit fixes
Fixed a real bug: nexler update used to stop entirely at the first failing check, silently discarding the results of every check before it and skipping every one after it — so a single file nexler couldn't positively identify (even a false positive) blocked every unrelated retrofit in the same run. It's now best-effort: every check runs regardless of earlier failures, and the summary reports "updated"/"already up to date"/"failed" per check; the command still exits non-zero if anything failed, but no longer at the cost of hiding what succeeded.
Fixed a false positive in the mongo: embedded-field filter fix check: its "already current" anchor was written with non-gofmt whitespace, so any app whose mongo/mongo.go had since been reformatted by normal Go tooling (editor format-on-save, gofmt, CI) — virtually guaranteed — was wrongly reported as "hand-rewritten" even though the code was unchanged. mongo.go.tmpl's own baked-in formatting for this block (and EnsureUniqueIndex's) is now real gofmt style too, so freshly-scaffolded apps no longer ship non-idiomatic whitespace in the first place.
New retrofit check: mongo: Filter{And, Or, Eq} + EnsureUniqueIndex/EnsureTTLIndex backfills the composable AND/OR/Eq filter-expression type and the two index helpers into an app's mongo/mongo.go if it predates them — previously no such check existed, so an older app had no path to picking this feature up other than hand-building an equivalent (as more than one app independently ended up doing).
Tags: update, mongo, fix
kgate: one shared WebSocket connection instead of one per channel
Fixed a real bug: kgate.Subscribe used to dial its own WebSocket connection per channel (tracked in a per-channel activeSubs map[string]context.CancelFunc) — harmless for a single channel, but kgate's gateway allows only one live connection per X-Client-Id, so subscribing to a second channel evicted the first connection, and vice versa, an endless reconnect churn for any app listening to more than one channel. Ported from a real fix already shipped in a live Klivolks app's own kgate client: Subscribe/Unsubscribe/ResumeAll now add to and remove from one shared subscription set (channels map[string]struct{} behind subMu), multiplexed over a single shared connection (active *websocket.Conn behind connMu) maintained by one reconnect-loop goroutine, started at most once per process (ensureLoopStarted). Register, HandleWebhook, Publish, and handleEvent (the documented hand-edit point for event-processing logic) are untouched. Existing apps pick this up via nexler update's new ensureKgateSharedConnection check — a narrow, anchor-based patch of the exact original Subscribe/Unsubscribe/ResumeAll block, same precedent as ensureKgateResumeAll, refusing (naming the file) if that block has been hand-rewritten.
Tags: kgate, bugfix
mongo.Update — a partial-patch counterpart to Set
New: -db mongo apps' mongo package gains Update[T any](ctx, coll, filter, patch) error — closes a real gap, since Set was the only existing "modify an existing document" operation and it's a full-document ReplaceOne-with-upsert, not a partial patch. Update reuses the existing structToBSON helper (the same non-zero-field, embedded-struct-flattening reflection walk filterToBSON already runs) to build a $set document from patch's non-zero fields, then calls the driver's UpdateOne — deliberately struct-based rather than taking a raw bson.M/driver-options parameter, matching every other function in this file and mirroring the SQL packages' own Update (non-zero-field patch, one matching document) rather than introducing a first-of-its-kind raw-driver-type exposure. Refuses an empty filter (would match every document) and a patch with no non-zero fields (nothing to set), same guard rails as SQL's Update. Doesn't cover Mongo-native update operators ($inc, $push, etc.) — those still need db.Mongo(name) directly. Existing apps pick it up via nexler update (ensureMongoUpdate) — append-only, same precedent as InsertID's own retrofit: wholly new code, nothing in mongo.go to sanity-check before appending.
Tags: mongo, scaffolding
Mongo Filter gains Eq, for explicit zero-value matches
-db mongo apps' mongo.Filter{And, Or []any} (added in an earlier pass, but never documented here) gains a third form, Eq map[string]any — explicit key:value pairs included in the query verbatim, zero values included, for the one case a struct filter can't express (struct filters drop any zero-valued field, so Widget{IsDeleted: false} silently contributes nothing; Filter{Eq: map[string]any{"isDeleted": false}} does what you'd expect). A single Filter now sets exactly one of And, Or, or Eq (previously just And/Or). Ported from a real bug found in a live Nexler app, where a by-ID-or-OrgId account lookup's soft-delete exclusion was silently a no-op for exactly this reason. Template-only for now — Filter{And, Or} itself was never added to nexler update's retrofit list when it first shipped, so neither it nor Eq currently backfills into already-scaffolded apps; only apps scaffolded (or updated for this specifically, once that check exists) after this change get it.
Tags: mongo, bugfix
openapi.Operation gains QueryType, for query params on non-GET routes
Fixed a real bug: openapi.Spec only ever auto-detects query parameters from Operation.ReqType when Method is "GET" — a DELETE/POST/PUT route with a real query-string field (e.g. a hard-delete route's ?hard=true) never showed it in the generated spec/Swagger UI no matter what was passed as ReqType, since non-GET methods only ever document ReqType as a JSON request body. Operation gains a new field, QueryType any — a zero-value struct documented as query parameters independently of ReqType, for exactly this case. Only needed on non-GET operations with real query fields; a GET's ReqType is already handled automatically, so QueryType is redundant there. Found and fixed in a live Nexler app's own DELETE /accounts/{id}?hard=true route.
Tags: openapi, bugfix
Real JWT revocation: core/tokens.go, mongo.EnsureTTLIndex, and a RequireAuth check
New, for -auth jwt|both apps with -db mongo: a generic token-revocation primitive, so a hand-written POST /auth/logout handler has real revocation to call instead of building its own blocklist. core/tokens.go gains RevokeAllTokens(ctx, subject) and IsTokenRevoked(ctx, subject, issuedAt), storing one {subject, revokedAt} marker per subject (collection core_revoked_tokens) rather than a per-token id — auth.Claims has no jti, so a single marker covers both the access token and any refresh token issued alongside it in one check (a token is invalid if its iat is at or before the subject's marker). RequireAuth now calls IsTokenRevoked right after a successful auth.VerifyJWT, in every JWT-verifying branch (jwt and both, with and without -merge-service-auth) — gated out entirely for -auth session-only or non-Mongo apps, so no dangling reference is ever generated. mongo/mongo.go gains a sibling to EnsureUniqueIndex, EnsureTTLIndex(ctx, coll, field, seconds), used to auto-expire each marker 30 days after revokedAt (the longest any token can live) so revocation state doesn't outlive anything it could still affect. Ported from a live Nexler app's own POST /auth/logout implementation. Template-only, same scope note as the Filter.Eq entry below — no nexler update retrofit entry, so only newly-scaffolded apps get this; and SQL-backed (-db mysql|postgres|mssql) apps don't get core/tokens.go at all yet, since the TTL-index mechanism it relies on has no SQL-dialect equivalent, unlike core/services.go's dual Mongo/SQL support.
Tags: auth, mongo, security
core_services gains last_used_at, plus two missing DELETE rows in these docs
New: core.Service/ServiceSummary gain LastUsedAt *time.Time (last_used_at on the wire) — the timestamp of a service account's most recent authenticated use, surfaced on GET /admin/services (list + detail) as a staleness signal before hard-deleting a key. Recorded inside core.VerifyServiceKey itself — the one function both middleware.RequireServiceAuth and middleware.RequireAuth's own X-Api-Secret fallback call — via a new unexported touchServiceLastUsed, fired with go and never awaited, so a slow or failed write never delays or fails the authenticated request that triggered it. Mongo-backed apps only for now: the SQL branch gains the same field (so ServiceSummary's shape stays identical across every -db choice) but it's always nil there — recording it would need a new stored procedure plus a schema column across mysql/postgres/mssql, unlike the rest of core/services.go's existing dual-dialect support. Also fixed a documentation gap while in here: the Admin API table above never listed DELETE /admin/services/{name} or DELETE /admin/users/{id}, even after both shipped in an earlier pass.
Tags: auth, mongo, docs
-merge-service-auth — fold service-key auth into RequireAuth
New opt-in flag on nexler create app (only meaningful with -auth jwt|both and -db): folds X-Api-Secret service-key auth into middleware.RequireAuth itself, tried after JWT/session, instead of generating a separate middleware.RequireServiceAuth — so a service/automation caller can hit the exact same -protected routes a human user would, without a route needing a service-only variant of itself. A matching service key still attaches auth.ContextWithService plus auth.ContextWithSubject (set to the service's name). Off by default — the separate-middleware design stays the right choice for a pure API app that wants user-only and service-only routes kept structurally distinct. Retrofit an already-scaffolded app with the new nexler update -merge-service-auth flag, a deliberately separate, explicit opt-in step — never run automatically by a plain nexler update, and it refuses (naming the file) if middleware/service_auth.go has been hand-edited.
Tags: auth, service-auth
-own-register — an independent second resource in one package
New opt-in flag on nexler create <route>, combined with a not-yet-existing -file and a required -name: scaffolds that file as a fully independent second (third, ...) resource inside an already-existing package, instead of folding its method(s) into the package's one existing Register function (Go only allows one func Register per package). The new resource gets its own Register<name> function, own middleware/openapi imports, own service/store/model files, and an additional wiring call in the aggregator alongside the package's existing one (e.g. adminproviders.Register(mux) then adminproviders.RegisterSms(mux), sharing one import). Mirrors a pattern already hand-built in a live Nexler app before this flag existed — two resources sharing one package, the second one hand-written with its own RegisterSms because no scaffold path for it existed yet. A later nexler create <route> targeting that same -file again correctly extends its own Register<name>, without repeating -own-register. Off by default — every existing -file/-name combination keeps behaving exactly as before.
Tags: routes, scaffolding
Mongo filter fix, store/common.Base, and richer HTML responses
Three related fixes/additions, all ported from patterns already proven out in live Nexler apps. Fixed a real bug: mongo's Get/GetOne/Set/Delete filter builder didn't flatten an anonymously embedded struct field into the top-level filter (only InsertID's separate field-locator did), so Widget{Base: common.Base{ID: id}} silently built {"base": ...} instead of {"_id": id} — every by-ID lookup through an embedded base struct was broken. New store/common.Base (-db mongo apps): a small shared ID bson.ObjectID struct meant to be embedded anonymously in every domain type, instead of every model redeclaring its own ID field. Richer HTML responses: response.HTML's page data gains Subject/Path, layout.html can reference three optional Header/Sidebar/Footer partials, and two new functions, HTMLError/Unauthorised, render a styled error page instead of the plain JSON envelope (falling back to it if the page itself can't render). All three existing apps pick up via nexler update — the mongo fix and the HTML upgrade are exact anchor-based patches of otherwise-identical generated code (refusing, naming the file, if it's been hand-rewritten); store/common.Base is written only if missing.
Tags: mongo, html, bugfix
-multitenant — thread a tenant Org through auth, session, and core.User
New opt-in flag on nexler create app (only meaningful with -auth jwt|session|both — errors with -auth none), generalizing a pattern already proven in a live Nexler app: threads a tenant Org through auth.ContextWithOrg/Org (a new context key pair, distinct from Subject), StartSession/SessionFromRequest's org parameter (when -auth includes session), and core.User.OrgId (when a core database connection and a JWT-capable -auth choice are both present). auth/jwt.go's Claims.Org field and IssueJWT's org parameter were already unconditional from an earlier pass, so a JWT-only app needs no further wiring. A service-key-authenticated request never gets an Org attached — a service isn't tied to a tenant org. core_users also gains an org_id column, provisioned unconditionally by nexler init db for every -db app (zero-cost when unused, same precedent as core_kgate_channels), including an idempotent ALTER TABLE for databases provisioned before this column existed. Retrofit an already-scaffolded app with the new nexler update -multitenant flag, a deliberately separate, explicit opt-in step — never run automatically, and it refuses (naming the file) if auth/context.go, auth/session.go, middleware/auth.go, or core/users.go has been hand-edited. Along the way, fixed a pre-existing bug in the unrelated ensureAuthSubjectContext retrofit (nexler update's automatic auth/context.go-creation path): it rendered auth/context.go.tmpl without the HasCoreDB/AuthKind fields that template's service-key block already depends on, which would fail template execution for an app old enough to hit that path and new/DB-enabled enough to have a JWT-capable core DB.
Tags: auth, multitenant, bugfix
-auth none stub: TODO removed, honest doc comment
The -auth none branch of generated middleware.RequireAuth carried a // TODO: verify apiKey and token against real credentials. comment left over from before -auth existed — but this stub structurally has nothing to verify against (no core_services, core_users, JWT, or session package is ever generated for -auth none), so the TODO could never be resolved as written. The comment now says plainly that -auth none performs no real verification by design, and points at -auth jwt|session|both for a real implementation. Also fixed a stray X-Api-Secret/X-Api-Secret naming mismatch in the same comment (the code has always checked X-Api-Secret). No behavior change; not retrofitted to existing apps, same precedent as the comment's previous revision.
Tags: auth, docs
kpass.Authorise — resolve a login code via kpass
New function in the generated kpass client (nexler init kpass): Authorise(ctx, code) GETs kpass's separate {KPASS_URL}/api/v1/authorise endpoint (query params, not headers) to resolve a one-time login/auth code from the frontend into the calling user's identity, returning a flat AuthoriseResult{UserId, UserType, UserName, UserRole, OrgId}. Generated unconditionally, same as Check/Allowed — independent of the app's -auth choice.
Tags: kpass, auth
{APPNAME}_API_BASE_PATH — OpenAPI servers for gateway-mounted apps
New Config.APIBasePath setting, unset by default (no fallback — an operator deploying behind an API gateway sets it explicitly). When set, openapi.Spec now emits a relative servers[0].url entry, so Swagger UI resolves requests correctly when the app is reverse-proxied under a path prefix (e.g. a gateway mounting it at /api/<service>) instead of only working at the origin root. Purely documentational — doesn't affect actual route registration or matching. Existing apps pick it up via nexler update.
Tags: config, openapi
KGate worker module; core DB init fix
Fixed a core database initialization issue and continued building out the KGate worker module.
Tags: kgate, fix
Docs site published
Added this guide (docs/) as the first end-user-facing documentation for Nexler, styled to match klivolks.com. Verified every command/flag against cmd/nexler/*.go directly rather than relying on CLAUDE.md's summary, which was found to omit init docker, init ci, and update from its compact usage block.
Tags: docs
-name flag; cross-invocation identifier collision fix
Fixed a scaffolding bug where re-running nexler create <route> to add a second, distinct route under an already-scaffolded package's -module/-submodule could silently generate the same handler function, Request/Response types, and OperationID as an existing route (identifiers were derived purely from -module/-submodule + verb, never the URL path). This now fails fast with an error naming every colliding identifier, before anything is written. New -name flag on nexler create <route> disambiguates identifiers for this case without changing where the route's files live.
Tags: create-route, fix
nexler init kube
New command: adds k8s/deployment.yaml (Secret + Deployment + Service) to an existing app, completing the container pipeline started by init docker/init ci. -registry github derives the image reference from go.mod's module path; -registry dockerhub prompts for a Docker Hub username; -image overrides either. The generated file is gitignored, since its Secret document embeds real values from .env.
Tags: kube, deploy
Swagger on/off switch; kgate webhook OpenAPI docs + test subscribe
New {APPNAME}_SWAGGER_ENABLED setting (default true) gates /swagger and /openapi.json, for disabling both in production. nexler init kgate's Register now documents POST /webhooks/kgate in /openapi.json/Swagger UI (previously the one generated route invisible there) and subscribes to a "test" channel on startup as a built-in connectivity smoke test. Existing apps pick up both via nexler update.
Tags: kgate, openapi, config
API-key (service-to-service) auth; core_users/core_services
Apps with -auth jwt|both and -db set now get middleware.RequireServiceAuth, a second auth mechanism (checking X-Api-Secret against a new core_services table) wholly independent of RequireAuth, for app-to-app calls. core.CreateService issues a key once, storing only its hash. A companion core_users table (UserId matching the JWT sub claim, plus Username/UserRole/UserType/Status) is a minimal local record, not a profile store. Both tables are provisioned by nexler init db; existing apps pick up the Go code via nexler update.
Tags: auth, core, security
Admin API for users/services; hidden Swagger button when off; usage examples added
New Swagger-documented admin API (GET/POST /admin/users, GET/PATCH /admin/users/{id}, GET/POST /admin/services, GET /admin/services/{name}, POST /admin/services/{name}/revoke) for every -auth jwt|both + -db app, wrapping core.ListUsers/ListServices/GetService (new) alongside the existing core functions — authentication only (middleware.RequireAuth), authorization deliberately left as a TODO for kpass. The homepage's "View API Docs" button now hides itself client-side when SWAGGER_ENABLED=false. This page also gained real Go usage examples (not just CLI commands) for kpass, kgate, JWT/session auth, and service auth.
Tags: admin-api, docs, ui
-file on create <route> now creates a real second file
Fixed: adding a second, distinct route to an already-scaffolded -module/-submodule package with a different -file value used to silently ignore that value and append everything into the original file. It now creates a genuine new handler+model file pair when -file names one that doesn't exist yet, while Register/OpenAPI wiring stays centralized in the package's one primary file (Go permits only one Register per package). Identifier-collision checks (-name) and HTML content-file naming are now scoped to the whole package instead of a single file, closing a related bug where a second -response html route could silently reuse the first route's content file.
Tags: cli, routes, bugfix
-file, OpenAPI tags, -response raw, -jwt-secret, init docker/init ci, update
Additive, backward-compatible release: new -file flag, OpenAPI operation tags and client-ID auth support, response.JSONRaw (-response raw), the -jwt-secret reuse flag, the nexler init docker/nexler init ci commands, and nexler update for retrofitting existing apps.