platform-shared

Shared platform foundations for authentication, profiles, and notifications across social, travel, workout, and basa.

Documentation site: https://charles2ke.github.io/platform-shared/ (published from docs/).

Architecture overview

This package is intentionally framework-light and dependency-free. Core business logic lives in reusable modules under src/, while app-specific HTTP, queue, or serverless integration should wrap these modules in each downstream repository.

src/
  auth/            JWT issuing/verification, refresh pattern, route guards, RBAC helpers
  profile/         Canonical profile model validation plus CRUD service and memory adapter
  notifications/   Unified send/schedule API, template rendering, channel adapters
  shared/          Environment config, structured errors, logging hooks
  adapters/        Framework/provider adapters: HTTP middleware, HTTP channel, worker loop
examples/          Integration stubs for social, travel, workout, and basa

Module responsibilities

Auth

Profile

Notifications

Adapters

Runtime

Cache

Shared

Environment variables

Copy .env.example and set values in each app environment.

Variable Required Purpose
PLATFORM_JWT_SECRET Production yes JWT HMAC secret; use at least 32 random characters.
PLATFORM_JWT_ISSUER No JWT issuer, defaults to platform-shared.
PLATFORM_JWT_AUDIENCE No App or API audience to verify.
PLATFORM_JWT_ACCESS_TTL_SECONDS No Access token TTL, defaults to 900 seconds.
PLATFORM_JWT_REFRESH_TTL_SECONDS No Refresh token TTL, defaults to 30 days.
PLATFORM_DEFAULT_LOCALE No Profile default locale, defaults to en-US.
PLATFORM_DEFAULT_TIMEZONE No Profile default timezone, defaults to UTC.
PLATFORM_DEFAULT_FROM_EMAIL No Default email sender for provider adapters.
PLATFORM_DEFAULT_SMS_SENDER No Default SMS sender for provider adapters.
PLATFORM_DEFAULT_PUSH_SENDER No Default push sender for provider adapters.

Usage snippets

Issue and verify auth tokens

import { issueTokenPair, createAuthGuard } from '@charles2ke/platform-shared/auth';

const tokens = issueTokenPair({
  subject: 'user-123',
  roles: ['member'],
  permissions: ['profile:read'],
  secret: process.env.PLATFORM_JWT_SECRET,
  issuer: 'platform-shared',
  audience: 'social'
});

const guard = createAuthGuard({
  secret: process.env.PLATFORM_JWT_SECRET,
  issuer: 'platform-shared',
  audience: 'social'
});

const principal = guard(request, { permissions: ['profile:read'] });

Rotate, revoke, and map roles to permissions

import {
  createAuthGuard,
  createRoleRegistry,
  describeToken,
  InMemoryTokenRevocationStore,
  rotateTokenPair
} from '@charles2ke/platform-shared/auth';

const revocationStore = new InMemoryTokenRevocationStore();
const roleRegistry = createRoleRegistry({
  member: ['profile:read'],
  moderator: { permissions: ['post:delete'], inherits: ['member'] }
});

const guard = createAuthGuard({ secret, issuer: 'platform-shared', audience: 'social', revocationStore, roleRegistry });

// Refresh endpoint: rotate the pair, revoke the presented refresh token, and
// treat a replayed refresh token as a compromise (all sessions are revoked).
const rotated = rotateTokenPair(refreshToken, {
  secret,
  issuer: 'platform-shared',
  audience: 'social',
  revocationStore,
  onReuseDetected: ({ subject }) => securityLog.warn('refresh token replay', { subject })
});

// Session/introspection endpoint.
const session = describeToken(principal.claims); // { expiresAt, expiresInSeconds, expired, ... }

// Inherited roles are available on principal.effectiveRoles.
guard(request, { roles: ['member'] });

// Logout endpoints.
revokeSession(principal.claims, { revocationStore }); // ends this login (access + refresh)
revocationStore.revokeToken(principal.claims);        // single token
revocationStore.revokeSubject('user-123');            // everywhere

Enforce RBAC inside services, jobs, and consumers

import { createAccessPolicy } from '@charles2ke/platform-shared/auth';
import { ProfileService } from '@charles2ke/platform-shared/profile';

const policy = createAccessPolicy({
  'profile.get': { permissions: ['profile:read'] },
  'profile.update': { permissions: ['profile:write'] },
  'profile.delete': { roles: ['admin'] }
}, { roleRegistry });

const profiles = new ProfileService({ store, policy });

await profiles.update(id, { timezone: 'Africa/Nairobi' }, { principal });

Mount guards and providers in a consumer repo

import { createExpressAuthMiddleware, createNotificationWorker, HttpChannelAdapter, replayDeadLetters, withFetchAuth } from '@charles2ke/platform-shared/adapters';

app.get('/feed', createExpressAuthMiddleware(guard, { requirements: { roles: ['member'] } }), handler);

export const GET = withFetchAuth(routeHandler, guard, { permissions: ['profile:read'] });

const notifications = new NotificationService({
  adapters: { email: new HttpChannelAdapter({ channel: 'email', endpoint: process.env.EMAIL_WEBHOOK_URL, headers: { authorization: providerKey } }) },
  scheduler,
  deadLetterStore
});

const worker = createNotificationWorker(notifications, { intervalMs: 60_000 });
worker.start();

await replayDeadLetters({ service: notifications, store: deadLetterStore });

Manage profiles

import { ProfileService } from '@charles2ke/platform-shared/profile';

const profiles = new ProfileService({ defaults: { locale: 'en-US', timezone: 'UTC' } });

const profile = await profiles.create({
  displayName: 'Charles',
  contact: { email: 'charles@example.com' },
  preferences: { units: 'metric' }
});

await profiles.softDelete(profile.id);
await profiles.restore(profile.id);

const page = await profiles.search({ query: 'charles', limit: 20 });
const next = await profiles.search({ query: 'charles', limit: 20, cursor: page.nextCursor });

Plug in persistent stores and providers

import { ProfileStore } from '@charles2ke/platform-shared/profile';
import { ChannelAdapter } from '@charles2ke/platform-shared/notifications';

class SqlProfileStore extends ProfileStore {
  async create(profile) { /* app-owned persistence */ }
  async get(id) { /* ... */ }
  async update(id, profile) { /* ... */ }
  async delete(id) { /* ... */ }
  async list() { /* ... */ }
}

class EmailProviderAdapter extends ChannelAdapter {
  async send(message) { /* call provider, return a delivery status object */ }
}

Unimplemented interface methods throw structured PlatformErrors instead of failing silently.

Fallback channels and quiet hours

import { NotificationService, quietHoursFromProfile } from '@charles2ke/platform-shared/notifications';

await notifications.send({
  id: 'trip-reminder-42',
  channels: ['push', 'sms', 'email'],
  strategy: 'fallback',
  quietHours: quietHoursFromProfile(profile), // e.g. 22:00-07:00 in the profile's timezone
  body: 'Your flight boards in 3 hours'
});

Throttle failed logins

import { createLoginThrottle } from '@charles2ke/platform-shared/auth';

const throttle = createLoginThrottle({ maxAttempts: 5, windowMs: 15 * 60_000, lockoutMs: 15 * 60_000 });

function login(email, password, ip) {
  const keys = [`account:${email.toLowerCase()}`, `ip:${ip}`];
  keys.forEach((key) => throttle.assertAllowed(key)); // throws AUTH_LOGIN_LOCKED (429)
  if (!checkPassword(email, password)) {
    keys.forEach((key) => throttle.recordFailure(key));
    throw new Error('Invalid credentials');
  }
  keys.forEach((key) => throttle.recordSuccess(key));
}

Send notifications

import { CHANNELS, MockChannelAdapter, NotificationService } from '@charles2ke/platform-shared/notifications';

const notifications = new NotificationService({
  adapters: {
    [CHANNELS.EMAIL]: new MockChannelAdapter({ channel: CHANNELS.EMAIL }),
    [CHANNELS.PUSH]: new MockChannelAdapter({ channel: CHANNELS.PUSH })
  }
});

await notifications.send({
  channels: [CHANNELS.EMAIL, CHANNELS.PUSH],
  to: { email: 'user@example.com', userId: 'user-123' },
  subject: 'Welcome ',
  body: 'Hi , your account is ready.',
  variables: { name: 'Charles' }
});

Schedule notifications with retries

import { InMemoryNotificationScheduler, NotificationService } from '@charles2ke/platform-shared/notifications';

const scheduler = new InMemoryNotificationScheduler(); // swap for a queue-backed adapter
const notifications = new NotificationService({
  adapters,
  scheduler,
  maxScheduleAttempts: 4,
  retryDelayMs: 30_000,
  retryBackoffFactor: 2,
  maxRetryDelayMs: 15 * 60_000,
  deadLetterStore, // durable record of exhausted retries, replayable later
  onDeadLetter: ({ notification, attempts, reason }) => auditLog.write({ notification, attempts, reason })
});

await notifications.schedule(reminder, new Date(Date.now() + 60_000));

// Cron/worker loop
const { processed, retried, deadLettered, pending } = await notifications.dispatchScheduled();

// Cancel queued deliveries when the underlying event changes.
await notifications.listScheduled();
await notifications.cancelScheduled(reminder.id);

Run a background job on a schedule or on demand

import { createBackgroundWorker } from '@charles2ke/platform-shared/runtime';

const worker = createBackgroundWorker({
  name: 'profile-reindex',
  handler: async ({ trigger }) => reindexProfiles({ trigger }),
  intervalMs: 5 * 60_000,
  timeoutMs: 60_000,
  runOnStart: true,
  logger,
  onError: (error) => metrics.increment('profile_reindex_failed', { code: error.code })
});

worker.start(); // long-running process

// On demand: admin endpoint, CLI command, or external cron trigger.
const run = await worker.runOnce({ trigger: 'admin', requestedBy: principal.id });
if (run.status === 'skipped') {
  // a run was already in flight
}

worker.getStats(); // { runs, failures, skipped, lastDurationMs, ... }
worker.stop();

Downstream integration approach

  1. Install or vendor this package in the consuming app.
  2. Load app-specific env vars with loadConfig() or the app’s existing config layer.
  3. Wrap createAuthGuard() in the app’s router middleware layer.
  4. Replace in-memory stores/adapters with app-owned persistence and provider adapters by extending AccountStore, ProfileStore, ChannelAdapter, NotificationScheduler, or TokenRevocationStore (or supplying objects with the same methods).
  5. Keep domain-specific behavior in the app; keep shared identity/profile/notification contracts here.

See examples/social.js, examples/travel.js, examples/workout.js, and examples/basa.js for starting points. They are executable stubs covered by tests/examples.test.js:

Example Shows
social.js Login, guarded routes (including Express middleware), refresh-token rotation with replay detection, session introspection, session/single-token/global logout, role registry.
workout.js Role-derived and inherited-role permissions, authorize() in service code, scheduled push nudges with exponential backoff, cancellation, and dead lettering.
travel.js Immediate and scheduled multi-channel reminders drained by createNotificationWorker(), plus pending listing, cancellation, dead-letter capture, and replay.
basa.js RBAC-guarded order operations, policy-enforced profile CRUD (createAccessPolicy()), and scheduled email/SMS order updates with pending listing and cancellation.

Migration/adoption checklist

social

travel

workout

basa

Testing and local run instructions

This repository uses Node’s built-in test runner and has no external runtime dependencies.

npm test           # unit and example tests
npm run build      # syntax checks across src, tests, examples, scripts
npm run check      # build + test (run this before opening a pull request)
npm run test:coverage  # tests with Node's experimental coverage report
npm run audit          # production dependency audit (high severity and above)

npm run build performs syntax checks across source, tests, examples, and scripts.

TypeScript declarations

Type declarations are generated from the JSDoc in src/ with the typescript dev dependency and are not committed:

npm run types        # emit .d.ts files into types/ (also runs on npm install/prepare and before publish)
npm run check:types  # type-check the TypeScript consumer tests against the JSDoc-derived types

Every exports subpath has a matching types entry, so import { verifyToken } from '@charles2ke/platform-shared/auth' is typed in TypeScript and editor tooling.

Enterprise readiness

Dependencies and supported runtimes

Automated controls

Control Where Trigger
Tests + syntax checks on Node 22/24 .github/workflows/ci.yml push, pull request, manual
Production dependency audit .github/workflows/ci.yml push, pull request, manual
CodeQL analysis GitHub code scanning default setup push, pull request, weekly
Dependency version updates .github/dependabot.yml weekly
Documentation site deploy .github/workflows/pages.yml push to main touching docs/

Workflows declare least-privilege permissions and check out without persisting credentials.

Hardening built into the modules

Operator checklist

See SECURITY.md for the vulnerability reporting process and the full security model.

Documentation site

docs/index.html is a dependency-free single-page site covering every module, feature, and hardening control in this repository. It is deployed to GitHub Pages by .github/workflows/pages.yml whenever docs/ changes on main. Enable it once under Settings → Pages → Build and deployment → GitHub Actions. Update the site alongside README.md whenever public behavior changes.

Architecture decisions and next steps

Recommended next steps:

  1. Publish the package or configure each app to consume it from GitHub.
  2. Add persistent adapters for each app’s user/account/profile data store.
  3. Add real email, SMS, and push adapters behind the existing notification channel interface (HttpChannelAdapter covers HTTP providers).
  4. Standardize role and permission names across social, travel, workout, and basa.