@thecodeorigin/auth
v0.0.12
Published
THECODEORIGIN Authentication Portal client module
Downloads
513
Keywords
Readme
@thecodeorigin/auth
Shared Nuxt authentication and authorization for THECODEORIGIN applications. ID verifies the account through OIDC authorization code + PKCE. Each application then creates its own Better Auth session in its own KV storage.
Session behavior
- Signed, host-only, application-specific opaque cookies identify KV sessions.
Better Auth adds
__Secure-to the configured cookie name on HTTPS; consumers should use the session API rather than reading the configured base name. - Identity, organization access, abilities and entitlement are captured at login. Organization switching selects the saved organization abilities locally.
- Sessions have an absolute expiry (seven days by default). Reading a session, using an application, or renewing an ID session never extends that deadline.
- Signing out of ID or choosing a different ID account does not affect an application's existing session. Signing out of an application ends only that application's session.
- Permission changes in ID take effect when the application authenticates again.
Set a shorter
sessionMaxAgeif the application needs a shorter snapshot lifetime. - Directory lookups and support impersonation are explicit online ID operations. An expired ID access credential can prevent those operations; it does not invalidate local application authentication or ordinary authorization.
- Account replacement and impersonation rotate the application session. The administrator's restoration handle retains the original session expiry.
Better Auth owns session creation, signed cookies, KV reads and revocation. Its
internal establishment endpoint is never exposed as an HTTP route. The module
preserves the registered /auth/callback URI and validates ID-token signature,
issuer, audience, nonce and subject in addition to PKCE and state.
Configure a Nuxt application
export default defineNuxtConfig({
modules: ['@thecodeorigin/auth', '@nuxthub/core'],
hub: { kv: true },
auth: {
domain: 'id.thecodeorigin.com',
sessionStorageBase: 'kv',
sessionCookieName: 'tco_my_application_auth',
sessionMaxAge: 60 * 60 * 24 * 7,
routes: {
login: '/auth/login',
signIn: '/auth/sign-in',
callback: '/auth/callback',
home: '/dashboard',
error: '/auth/login',
},
},
})Configure NUXT_PUBLIC_AUTH_CLIENT_ID and NUXT_AUTH_CLIENT_SECRET with the
application's confidential ID client. NUXT_AUTH_SESSION_SECRET may provide a
separate signing secret of at least 32 characters. If omitted, the module derives
an application-specific signing key from the client secret using HKDF. Rotating
that source secret invalidates existing application cookies. No new database,
ID session table or infrastructure seed is required.
Use a unique cookie name per application, including applications on different localhost ports. Cookies do not isolate ports. Storage keys also include the client ID and cookie namespace. Legacy unsigned module cookies are not accepted; the first visit after migration requires authentication.
Cloudflare KV is eventually consistent. Server expiry is authoritative even if KV retains a record. Revocation and concurrent mutations are not globally atomic; the module rechecks expected session and login intent before publishing changes.
Shared application APIs
const auth = useAuth()
await auth.signIn('/projects')
await auth.switchAccount('/projects')
await auth.logout() // revoke locally, clear cached data, navigate to the signed-out screen
await auth.switchOrganization(organizationId)
// Login cards retain application presentation; the module owns flow and errors.
const { error, loggedOut, loading, handleSignIn, handleUseAnotherAccount } = useAuthLogin()signOut() revokes the local session without navigation. It throws on failure;
callers must not display successful logout after a failed revocation.
logout() additionally performs a full navigation. Account and impersonation UI
should also use full navigation after successful identity changes to reset stores.
The module checks other tabs on focus and session-change notifications.
recoverSession() is for same-origin business API 401 handling. It returns false
only after confirming that the local session is absent. Network/service errors
preserve existing state. Capture useAuth() in a valid Nuxt context before the
request, and never call signOut() merely because an unrelated API returned 401.
Server helpers remain available through auto-imports and @thecodeorigin/auth/server:
getServerAuthSession, defineAuthenticatedHandler, defineAuthorizedHandler,
defineSensitiveAuthorizedHandler, defineAdminHandler, and CASL helpers.
getFreshServerAuthSession remains a compatibility alias for a current local KV
read; force does not contact ID. All authorization checks use the same snapshot.
Local session mutations require same-origin POST requests. The legacy GET logout route directs users to the login surface without mutating authentication.
Work on the module across the ecosystem locally
From packages/auth, install dependencies and build:
pnpm install
pnpm prepackFrom the ecosystem superproject:
node .ecosystem/scripts/auth-local.mjs link
node .ecosystem/scripts/auth-local.mjs status
export PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN=falseThe helper points all seven consumer node_modules/@thecodeorigin/auth links at
the built local package and records their previous targets under ignored local
state. It changes no dependency manifests, lockfiles, deployments or gitlinks.
The environment setting prevents pnpm's automatic dependency verification during
local Nuxt hooks from replacing the links with published packages. Rebuild the
module after edits and restart local consumer dev servers. An explicit install
may replace links; run link again afterward.
Restore installed versions with:
node .ecosystem/scripts/auth-local.mjs unlinkPublishing the new module and updating each application's version pin is a separate release step. The local link is for this ecosystem checkout, not a replacement for a published dependency in independently cloned applications. Vault's existing integration-key contracts are included in the source module.
Verify
pnpm test
pnpm lint
pnpm test:typesFocused tests exercise real Better Auth sessions across separate instances with shared KV, complete callback validation, fixed expiry, local organization access, account rotation, independent logout, support restoration and client recovery.
