npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@reflagged/shell

v2.3.0

Published

Shared app shell for Reflagged services — OIDC auth, SSO, app switcher

Readme

@reflagged/shell

Shared app shell for Reflagged services. Provides:

  • OIDC authentication (signin, callback, signout)
  • SSO session management (JWT cookie + Payload AuthStrategy)
  • /api/shell-info proxy for platform service catalog
  • BrandSwitcher component (app palette: icons, search, ⌘K / Ctrl+K)
  • Admin route SSO enforcement middleware

Every host app fulfils the reFlagged Shell Contract: the fixed routes, the .dark convention and the theme tokens the components rely on.

Published as a public npm package of compiled ESM (dist/, with type declarations). Next.js is optional: ./core and ./react run in any React app or Web-standard server.

Install

pnpm add @reflagged/shell

No transpilePackages entry is needed any more; an existing one is harmless to keep. next and payload are optional peers, needed only for the ./next and ./payload entries.

Configure the app's identity:

  • Next.js: via env vars (NEXT_PUBLIC_* are inlined at build time):

    | Variable | Purpose | |----------|---------| | NEXT_PUBLIC_RFLGD_APP_KEY | App key matching the platform catalog service value (highlights the current app as "aktuell") | | NEXT_PUBLIC_RFLGD_APP_LABEL | Display name in BrandSwitcher | | RFLGD_DEFAULT_USER_ROLE | Role for auto-created users (default: user) |

  • Other React apps: wrap the components in ShellProvider (see Outside Next.js). Without a provider the components fall back to the env vars above.

Changes in 2.2

  • Back-channel logout. The platform ends a module's sessions when "Einloggen als" starts or ends, on logout, when a booking ends or a person loses access (OpenID Connect Back-Channel Logout). Each app adds one route file and one rflgd.json field:

    // src/app/api/oidc/backchannel-logout/route.ts
    export { POST, dynamic, runtime } from '@reflagged/shell/api/oidc-backchannel-logout'
    "oidcBackchannelLogoutPath": "/api/oidc/backchannel-logout"

    The route must not sit behind the app's own auth gate. Sessions now keep the ID token's sid and their sign-in time; verifySessionCookie returns null for a session the platform logged out. Custom session stores call isSessionRevoked(session). Details in the contract.

Changes in 2.1

  • Dark mode. BrandSwitcher (trigger, palette, plates) and the NotificationBell badge follow a .dark class on an ancestor, with the dark values of the platform's own palette. Light rendering is unchanged; apps add no CSS.
  • reFlagged Shell Contract. The routes, dark-mode convention and theme tokens every host app provides, in one place.
  • describeShellContract in ./testing checks an app's routes against the contract in its vitest suite.

Changes in 2.0

  • Compiled dist/. The package ships ESM with type declarations instead of TypeScript sources; no transpilePackages entry is needed (an existing one is harmless). Every entry also loads under plain Node ESM, e.g. in a consumer's vitest.
  • New layers. ./core (framework-free handlers over Request/Response), ./react, ./next, ./payload and the test-only ./testing (sessionStoreConformance, needs vitest). The pre-2.0 paths keep working.
  • /api/shell-info answers no-session for an invalid session cookie too; 1.x answered invalid-session there. Clients that told the two apart only need to handle no-session.
  • RFLGD_SERVER_URL is read alongside NEXT_PUBLIC_SERVER_URL and wins when both are set (the first non-empty one counts), so non-Next modules need no NEXT_PUBLIC_ name.
  • platformRole survives a token refresh. 1.x dropped it from the session cookie when /api/shell-info refreshed the access token.
  • callbackUrl is restricted to paths on the app's own origin. Absolute URLs, //host, /\host and the like fall back to /admin; the callback checks the stored value again. safeCallbackPath in ./core applies the same rule.
  • The sign-in error page shows the provider's text only for a matching state. An error in the callback URL is shown only when it is a known OAuth code (otherwise unknown_error), and error_description only when the URL's state matches the browser's sign-in; otherwise the page uses its own fixed text.

Entry points

| Entry | Contents | |-------|----------| | @reflagged/shell/core | Framework-free: OIDC sign-in/callback/sign-out and shellInfo over Request/Response, ShellSessionStore + cookieSessionStore, config, notifier, settings, directory | | @reflagged/shell/react | Components (BrandSwitcher, TenantTheme, ServiceIcon, NotificationBell, ImpersonationCapsule) and ShellProvider | | @reflagged/shell/next | Next middleware and route handlers wrapping the core | | @reflagged/shell/payload | Payload auth strategy (createOidcStrategy, nextauthStrategy) | | @reflagged/shell/testing | Test-only: sessionStoreConformance, describeShellContract (imports vitest) |

The pre-2.0 paths keep working unchanged:

import { BrandSwitcher } from '@reflagged/shell/components/BrandSwitcher'
import { loadAppConfig } from '@reflagged/shell/config'
import { OIDC_COOKIE, loadOidcEnv } from '@reflagged/shell/auth/oidc-config'
import { verifySessionCookie } from '@reflagged/shell/auth/oidc-cookie'
import { refreshAccessToken } from '@reflagged/shell/auth/oidc-refresh'
import { nextauthStrategy, createOidcStrategy } from '@reflagged/shell/auth/nextauth-strategy'

Mapping the platform's role onto your own (roleForNewUser)

nextauthStrategy is createOidcStrategy() with no options — the role a newly created account gets is RFLGD_DEFAULT_USER_ROLE (or admin for the very first account). Call createOidcStrategy directly to decide that role yourself from the platform's view of the person, using the workspace role the platform put in the session:

import { createOidcStrategy, type NewUserContext } from '@reflagged/shell/auth/nextauth-strategy'

function roleForNewUser({ orgRole, isFirstUser }: NewUserContext): string {
  if (isFirstUser) return 'admin'
  // org_role is three-valued, not two: 'owner' | 'admin' | 'member' when a
  // membership row exists (both 'owner' and 'admin' administer the
  // workspace), or a *platform* role — 'superadmin' | 'reflagged_admin' |
  // 'tenant_admin' | 'member' — when it does not. Check for 'owner' as well
  // as 'admin': the person who books an instance is always created as
  // 'owner', never 'admin'.
  return orgRole === 'owner' || orgRole === 'admin' ? 'workspace-admin' : 'member'
}

export const oidcStrategy = createOidcStrategy({ roleForNewUser })

This callback runs only when an account is created, never on later sign-ins — see NewUserContext's doc comments in src/payload/strategy.ts for the full contract, including the isFirstUser branch and the null case for standalone operation.

Per-app route files + middleware

Each app keeps thin wrappers that re-export the handlers:

// src/app/api/oidc/signin/route.ts
export { GET, dynamic, runtime } from '@reflagged/shell/api/oidc-signin'

// src/middleware.ts
export { default, config } from '@reflagged/shell/middleware'

Other API re-exports: @reflagged/shell/api/oidc-callback, @reflagged/shell/api/oidc-signout, @reflagged/shell/api/shell-info, @reflagged/shell/api/oidc-backchannel-logout (POST).

Notifications (createNotifier, NotificationBell)

Since 1.4.0 a module can post notifications to the platform inbox. The base stores one inbox entry per recipient, renders and brands the mail, and delivers it through the tenant's sender. Modules send data, never HTML.

// server only — uses OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET
import { createNotifier } from '@reflagged/shell/notifications/notifier'

const notifier = createNotifier()
await notifier.notify({
  idempotencyKey: `absence-${absence.id}-approved`, // same key → no duplicate
  topic: 'kollega.absence.approved',               // <module>.<object>.<event>
  category: 'activity',                            // or 'transactional' (not opt-out-able)
  title: 'Urlaub genehmigt',
  body: '12.–16. Oktober',
  actionUrl: `https://kollega.acme.rfl.gd/abwesenheiten/${absence.id}`, // https, own or tenant domain
  actionLabel: 'Antrag öffnen',
  recipients: [{ email: requester.email }],        // or { userId } / { role: 'org:admins' | 'org:members' }
})

Recipients must belong to the booking's organization (403 otherwise); addresses without a platform account are skipped. The token comes from the client_credentials grant with scope notifications:write, which every module client of the platform may request. Errors throw NotifyError with the HTTP status and the base's error code.

Rich mails (blocks, since 1.9.0)

title, body and one button are enough for a short note. For anything with structure — a status, facts, a table, a transcript — send blocks. A module chooses the building blocks; how they look (colours, fonts, logo, spacing) comes from the tenant's branding, rendered by the base with React Email. There is no HTML and no style property, so every module's mail looks like it belongs to the tenant and renders in Outlook, Gmail and Apple Mail alike.

import { createNotifier, type Block } from '@reflagged/shell/notifications/notifier'

const blocks: Block[] = [
  { type: 'callout', tone: 'warning', title: 'Rückruf nötig', text: 'Weitergabe zugesagt' },
  {
    type: 'facts',
    items: [
      { label: 'Anliegen', value: 'Angebot für einen Onlineshop' },
      { label: 'Rückruf an', value: [{ text: '0721 952 795 78', href: 'tel:+4972195279578' }] },
      { label: 'Dauer', value: '1:05 Min.' },
    ],
  },
  {
    type: 'section',
    title: 'Gesprächsverlauf',
    tone: 'outlined',
    blocks: [
      {
        type: 'conversation',
        messages: [
          { speaker: 'Agent', side: 'end', text: 'Hallo, hier ist die digitale Assistenz.' },
          { speaker: 'Anrufer', text: 'Ich möchte bitte zurückgerufen werden.' },
        ],
      },
    ],
  },
]

await createNotifier().notify({
  idempotencyKey: `call-${call.id}-callback`,
  topic: 'voice.call.callback',
  category: 'transactional',
  title: 'Rückrufwunsch – Angebot Onlineshop',  // subject and heading
  body: 'Angebot für einen Onlineshop',          // short text for the inbox list
  blocks,
  actionUrl: `https://voice.acme.rfl.gd/calls/${call.id}`,
  actionLabel: 'Anruf öffnen',                   // rendered as the last button
  recipients: [{ role: 'org:admins' }],
})

| Block | Fields | Use for | |---|---|---| | heading | text, level? 1–3 | sub-headings inside the mail | | text | text, size? sm/md/lg, muted?, align? | paragraphs; line breaks are kept | | button | label, url, variant? primary/secondary, align? | actions — https on the booking's or tenant's domain (like actionUrl), or tel:/mailto: | | image | src, alt, width?, href?, align? | charts, screenshots — https on the booking's or tenant's domain | | callout | tone neutral/info/success/warning/danger, title?, text? | status banners; tone colours are fixed, not branded | | facts | items[{ label, value }] | label/value pairs | | list | items[], ordered? | bullet or numbered lists | | table | columns[{ label, align? }], rows[][] | tabular data, up to 8 columns / 200 rows | | quote | text, cite? | quoted statements | | conversation | messages[{ speaker, text, side?, time? }] | transcripts, chats; side: 'end' = the module's own side | | code | code, language? | logs, snippets (monospace) | | divider, spacer | size? | separation | | section | blocks, title?, tone? plain/muted/outlined | grouping | | row | columns[{ blocks, width? }] (2–4) | side-by-side content, e.g. key figures |

Every text/value/cell is a RichText: a plain string, or spans for emphasis and links — [{ text: 'fett', bold: true }, { text: ' und ' }, { text: 'Link', href: 'https://…' }]. Markdown is not interpreted.

Rules the base enforces (400 with the failing path otherwise): only the blocks above, no extra properties, links https/tel:/mailto:; images and button links only on the booking's or tenant's domains (inline span links may point to any https page, e.g. a source), at most 200 top-level blocks, 100 kB, and section/row nested three levels deep. The base also writes a plain-text part from the blocks and shows the full mail in the platform inbox. Without blocks, body is rendered as paragraphs as before. Types: @reflagged/shell/notifications/blocks.

Email: modules do not send mail themselves

Every mail a module sends to a person goes through notify(). A module configures no SMTP server, no mail adapter and no mail credentials — no @payloadcms/email-*, no nodemailer, no SMTP_* variables in the manifest or compose file. The base owns the sender per tenant (own SMTP server, Microsoft 365 or the platform's [email protected] with SPF/DKIM), the branding, the user's preferences, unsubscribe links and the delivery log.

  • category: 'transactional' for mails that must arrive (cannot be opted out of), 'activity' for everything else.
  • Only people with a platform account in the booking's organization can be reached. Mail to outsiders (a tenant's own customers, newsletters) is not supported — raise it with the platform team instead of adding a transport.
  • Passwords are not a module concern. Users sign in through the platform's SSO; password reset, invitations and 2FA live in the base. The local Payload login is a bootstrap fallback for the first admin only — never hand out local module credentials to customers, because the module cannot send them a reset mail.

The bell shows the unread count (from /api/shell-info) and links to the central inbox:

import { NotificationBell } from '@reflagged/shell/components/NotificationBell'

<NotificationBell />

Module settings (createModuleSettings, since 1.10.0)

Settings a module declares in its manifest (service-templates/<key>/manifest.json in the base, block settings) are stored per tenant in the base and edited by platform and tenant admins there. The module only reads them, server-side:

import { createModuleSettings } from '@reflagged/shell/settings'

export const settings = createModuleSettings()

// In a route, access function, job …
if (!(await settings.get('documents.enabled', true))) return forbidden()

// Where only a synchronous answer works (e.g. Payload `admin.hidden`):
const hidden = !settings.peek('documents.enabled', true)
  • Uses the module's own OIDC client (OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET) with client_credentials and scope settings:read; the base derives tenant and module from the token.
  • One request loads all values; they are cached for 60 s (ttlMs) and revalidated with an ETag. A change in the base reaches the module within that window.
  • Never throws, never blocks start-up. Each call to the base has a 3 s deadline (requestTimeoutMs); after a failure it waits 10 s (retryAfterMs) before asking again. Until the base has answered once, and whenever a value is missing or has another type, the fallback applies — pass the manifest default. After an outage the last good values stay in use.
  • Enforce switches on the server (API, access, jobs), not only in the UI.

Module secrets (createModuleSecrets, since 2.3.0)

Credentials of a module's integrations (API tokens, passwords) are settings of type secret in the manifest. Admins set them in the base (write-only, stored encrypted); the module fetches them server-to-server:

import { createModuleSecrets, ModuleSecretError } from '@reflagged/shell/secrets'

// Once per process. Server-only entry: a client bundle importing it fails at once.
export const secrets = createModuleSecrets<'lexware.api-token'>()

const token = await secrets.require('lexware.api-token') // throws when not set
const maybe = await secrets.get('lexware.api-token') // string | null
  • Same OIDC client as the settings, own scope settings:secrets and endpoint GET /api/modules/settings/secrets. The base derives tenant and module from the token and answers only for an active booking, so a module only ever gets its own secrets.
  • Own entry @reflagged/shell/secrets (not in core/settings); its browser condition resolves to a stub that throws on import. Still never pass a secret as a prop to a client component or into a response.
  • Cached for 60 s (ttlMs); the last good values survive outages; secrets.refresh() reloads now (e.g. after the third-party API answered 401).
  • ModuleSecretError.code: missing (not set — tell the user to add it under Einstellungen → Module), unavailable (base not reachable, nothing cached), unreadable (the base cannot decrypt: platform key missing or changed — the last good values stay cached, this only surfaces without a cache), unconfigured (OIDC env missing), browser. Messages name the key, never the value.
  • Never log a secret, never send it to the browser.

Groups, roles and access (@reflagged/shell/directory, since 1.11.0)

The base keeps a tenant's groups (manual or mirrored from Microsoft Entra) and assigns the roles a module declares in its manifest (roles, or "directoryAccess": true for a module that only reads groups). The module asks per request, server-side:

import { getUserAccess, hasRole, inGroup, listGroups, listGroupsResult } from '@reflagged/shell/directory'

const me = await getUserAccess(session.sub) // { access, groups, roles, known }, never throws
if (!hasRole(me, 'editor')) return forbidden()
const mayRead = inGroup(me, area.groupId) // store grants against the group id, never the name

const allGroups = await listGroups() // for share dialogs, `removed` included; [] when unknown

// Mirroring into your own tables: write only definitive answers.
const { known, groups } = await listGroupsResult()
if (known) await syncGroups(groups)
if (me.known) await syncMemberships(session.sub, me.groups)
  • known is true only when the values are a definitive base answer: fresh, or the last good one within its 60-minute window (a 404 is a known access: false). Every fallback has known: false — base unreachable with nothing usable cached, back-off without a cached answer, module does not take part (403), token refused, no OIDC client configured. Never write a mirrored state from an answer with known: false: an unknown answer has empty groups and roles, and writing it would empty a person's groups on every outage. listGroupsResult() gives the same flag for the group list.

  • Same OIDC client and env vars as the settings, scope directory:read.

  • On a cold cache getUserAccess waits for the base (up to a few seconds when it is slow). Call it once per request and pass the result down.

  • Cached per user for 5 minutes, then revalidated with an ETag; 3 s deadline per call, 10 s pause after a failure, at most 1 000 users in memory.

  • When the base cannot answer, the last good value is used for up to 60 minutes after it was fetched; after that, or when there never was one, the result is { access: true, groups: [], roles: [], known: false } ("unknown") — allow only what needs no role and no group. A 404 from the base is { access: false, groups: [], roles: [], known: true }.

  • A module that declares neither roles nor directoryAccess gets 403 from the base, and a token endpoint that refuses the directory:read token for good (HTTP 400 with invalid_scope or unauthorized_client) is treated the same: the client answers "unknown" and asks again only after 60 minutes. Every other token failure (401, 408, 429, 5xx, network) only pauses for 10 s. A denial already cached for a user stays in force during that hour.

  • Session enforcement. The Payload strategy (createOidcStrategy) stops accepting a session once the base definitively says access: false (or 404); the admin then falls back to /api/oidc/signin, which clears the session cookie and redirects to {base}/apps?error=no-access. The check uses the cache only and refreshes in the background, so it adds no latency and a slow or failing base never ends a session. RFLGD_DIRECTORY_ENFORCE=false turns the enforcement off; the client API keeps working. Apps that read the session cookie themselves (no Payload strategy) can call isSessionAccessRevoked(sub) the same way.

Outside Next.js (Vite, Hono, Remix)

Give the components their config through ShellProvider:

import { BrandSwitcher, ShellProvider } from '@reflagged/shell/react'

<ShellProvider config={{ appKey: 'botspawn', appLabel: 'Botspawn' }}>
  <BrandSwitcher />
</ShellProvider>

Serve /api/shell-info from any Web-standard server with a store over your own session handling:

import { Hono } from 'hono'
import { backchannelLogout, isSessionRevoked, loadOidcEnv, shellInfo } from '@reflagged/shell/core'
import type { ShellSessionStore } from '@reflagged/shell/core'

const sessions: ShellSessionStore = {
  // A session the platform logged out (back-channel logout) must not load.
  load: async (req) => {
    const session = await mySessions.read(req)
    return session && !isSessionRevoked(session) ? session : null
  },
  refresh: async (req, session) => mySessions.refreshTokens(session),
  save: async (req, session, res) => mySessions.write(session, res),
  end: async (req, res) => mySessions.clear(res),
}

const app = new Hono()
// platformUrl: the platform's base URL, i.e. the OIDC issuer without `/oidc`.
app.get('/api/shell-info', (c) => shellInfo(c.req.raw, { platformUrl: 'https://platform.example', sessions }))
app.post('/api/oidc/backchannel-logout', (c) => backchannelLogout(c.req.raw, { env: loadOidcEnv()! }))

sessionStoreConformance from @reflagged/shell/testing checks a store in your vitest suite, describeShellContract the app's routes (see the contract).

Releasing

Bump version in package.json, commit, then git tag vX.Y.Z && git push --tags. publish.yml builds dist/, typechecks, checks the tag matches version and puts it on npm (needs the NPM_TOKEN repo secret); fan-out.yml then opens a bump PR in every rfl-gd repo whose root package.json depends on this package and merges it unless the bump breaks a CI job that passes on the repo's default branch (a main that is red already does not block it; no CI at all merges, too). Re-run a rollout via Actions → Roll out @reflagged/shell → Run workflow; it resumes open PRs.

Needs the secret SHELL_FANOUT_TOKEN: a fine-grained token on rfl-gd, all repositories, with Contents and Pull requests read/write, Commit statuses and Actions read. PACKAGES_READ_TOKEN (read:packages) lets repos with private @rfl-gd packages resolve their lockfile. Running tenant instances stay pinned and update one by one in Base (Plattform → Updates).

App palette

BrandSwitcher opens on click or with ⌘K / Ctrl+K anywhere in the app. It shows every running app with its catalog icon and tagline, filters them as you type, and lists the user's workspaces. Platform admins get a "Plattform" section that links to the Base palette (<baseUrl>/?palette=<query>); the tenant switch itself runs in Base, where the platform session lives.

Apps that bind ⌘K / Ctrl+K themselves should drop their own binding.

The trigger is named by what it shows — app label, workspace — followed by "Apps wechseln", so speech input finds it by its visible text (WCAG 2.5.3). Style or query it with button[data-brand-switcher], not by its name (the open palette carries data-brand-switcher too).

Tenant branding

BrandSwitcher shows the tenant's logo mark and loads the tenant palette from the platform (org.themeCssUrl in /api/shell-info) as <link id="rflgd-tenant-theme">. Modules without the switcher render <TenantTheme /> from @reflagged/shell/components/TenantTheme once in the root layout.

The stylesheet defines, on :root:

  • --brass-50 … --brass-900 — RGB channels (125 85 26), the Reflagged brass scale re-tinted to the tenant colour. Every step keeps brass's luminance, so contrast pairs that work with brass keep working.
  • --rflgd-brand-primary — the raw tenant colour (decorative use only).

Point the module's own tokens at it, always with the brass fallback:

:root { --primary: rgb(var(--brass-700, 125 85 26)); }
.dark { --primary: rgb(var(--brass-400, 214 166 76)); }

or in Tailwind 3: primary: 'rgb(var(--brass-700, 125 85 26) / <alpha-value>)'. Text on a filled brand surface stays white on 700 (light) and dark on 400 (dark mode). Status and destructive colours do not follow the palette.

Local development (live-edit against a consumer)

A published package is frozen in node_modules. To iterate on the shell and a consuming app at the same time, add a local, uncommitted pnpm override in the consumer (all Reflagged repos sit side-by-side under ~/Development/):

// <app>/package.json — DEV ONLY, do not commit
"pnpm": {
  "overrides": {
    "@reflagged/shell": "link:../rflgd-shell"
  }
}

Then pnpm install. The consumer resolves exports to dist/, so run pnpm exec tsup --watch in the shell checkout while live-editing. Remove the override before committing — link:../rflgd-shell does not exist in the Coolify build context and would break the build.