@memberjunction/server 5.39.0 → 5.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/auth/index.js +1 -1
  2. package/dist/auth/index.js.map +1 -1
  3. package/dist/auth/magicLink/MagicLinkKeys.d.ts +58 -0
  4. package/dist/auth/magicLink/MagicLinkKeys.d.ts.map +1 -0
  5. package/dist/auth/magicLink/MagicLinkKeys.js +99 -0
  6. package/dist/auth/magicLink/MagicLinkKeys.js.map +1 -0
  7. package/dist/auth/magicLink/MagicLinkRouter.d.ts +33 -0
  8. package/dist/auth/magicLink/MagicLinkRouter.d.ts.map +1 -0
  9. package/dist/auth/magicLink/MagicLinkRouter.js +184 -0
  10. package/dist/auth/magicLink/MagicLinkRouter.js.map +1 -0
  11. package/dist/auth/magicLink/MagicLinkService.d.ts +123 -0
  12. package/dist/auth/magicLink/MagicLinkService.d.ts.map +1 -0
  13. package/dist/auth/magicLink/MagicLinkService.js +605 -0
  14. package/dist/auth/magicLink/MagicLinkService.js.map +1 -0
  15. package/dist/auth/magicLink/index.d.ts +6 -0
  16. package/dist/auth/magicLink/index.d.ts.map +1 -0
  17. package/dist/auth/magicLink/index.js +6 -0
  18. package/dist/auth/magicLink/index.js.map +1 -0
  19. package/dist/auth/magicLink/magicLinkCore.d.ts +82 -0
  20. package/dist/auth/magicLink/magicLinkCore.d.ts.map +1 -0
  21. package/dist/auth/magicLink/magicLinkCore.js +164 -0
  22. package/dist/auth/magicLink/magicLinkCore.js.map +1 -0
  23. package/dist/auth/magicLink/redeemLanding.d.ts +22 -0
  24. package/dist/auth/magicLink/redeemLanding.d.ts.map +1 -0
  25. package/dist/auth/magicLink/redeemLanding.js +61 -0
  26. package/dist/auth/magicLink/redeemLanding.js.map +1 -0
  27. package/dist/auth/magicLink/types.d.ts +131 -0
  28. package/dist/auth/magicLink/types.d.ts.map +1 -0
  29. package/dist/auth/magicLink/types.js +6 -0
  30. package/dist/auth/magicLink/types.js.map +1 -0
  31. package/dist/config.d.ts +411 -0
  32. package/dist/config.d.ts.map +1 -1
  33. package/dist/config.js +60 -0
  34. package/dist/config.js.map +1 -1
  35. package/dist/context.d.ts.map +1 -1
  36. package/dist/context.js +225 -2
  37. package/dist/context.js.map +1 -1
  38. package/dist/generated/generated.d.ts +877 -4
  39. package/dist/generated/generated.d.ts.map +1 -1
  40. package/dist/generated/generated.js +17779 -12750
  41. package/dist/generated/generated.js.map +1 -1
  42. package/dist/generic/ResolverBase.d.ts.map +1 -1
  43. package/dist/generic/ResolverBase.js +35 -7
  44. package/dist/generic/ResolverBase.js.map +1 -1
  45. package/dist/index.d.ts +2 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +25 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/resolvers/CurrentUserContextResolver.d.ts +9 -3
  50. package/dist/resolvers/CurrentUserContextResolver.d.ts.map +1 -1
  51. package/dist/resolvers/CurrentUserContextResolver.js +19 -5
  52. package/dist/resolvers/CurrentUserContextResolver.js.map +1 -1
  53. package/dist/resolvers/EntityResolver.d.ts.map +1 -1
  54. package/dist/resolvers/EntityResolver.js +13 -2
  55. package/dist/resolvers/EntityResolver.js.map +1 -1
  56. package/dist/resolvers/GenerateSeedTaxonomyResolver.d.ts +28 -0
  57. package/dist/resolvers/GenerateSeedTaxonomyResolver.d.ts.map +1 -0
  58. package/dist/resolvers/GenerateSeedTaxonomyResolver.js +100 -0
  59. package/dist/resolvers/GenerateSeedTaxonomyResolver.js.map +1 -0
  60. package/dist/resolvers/RunClusterAnalysisResolver.d.ts +74 -0
  61. package/dist/resolvers/RunClusterAnalysisResolver.d.ts.map +1 -0
  62. package/dist/resolvers/RunClusterAnalysisResolver.js +243 -0
  63. package/dist/resolvers/RunClusterAnalysisResolver.js.map +1 -0
  64. package/dist/resolvers/UserResolver.d.ts +16 -2
  65. package/dist/resolvers/UserResolver.d.ts.map +1 -1
  66. package/dist/resolvers/UserResolver.js +45 -2
  67. package/dist/resolvers/UserResolver.js.map +1 -1
  68. package/dist/rest/SignatureWebhookHandler.d.ts +19 -0
  69. package/dist/rest/SignatureWebhookHandler.d.ts.map +1 -0
  70. package/dist/rest/SignatureWebhookHandler.js +86 -0
  71. package/dist/rest/SignatureWebhookHandler.js.map +1 -0
  72. package/package.json +75 -71
  73. package/src/__tests__/magicLink.test.ts +387 -0
  74. package/src/auth/index.ts +2 -2
  75. package/src/auth/magicLink/MagicLinkKeys.ts +122 -0
  76. package/src/auth/magicLink/MagicLinkRouter.ts +209 -0
  77. package/src/auth/magicLink/MagicLinkService.ts +724 -0
  78. package/src/auth/magicLink/index.ts +17 -0
  79. package/src/auth/magicLink/magicLinkCore.ts +216 -0
  80. package/src/auth/magicLink/redeemLanding.ts +62 -0
  81. package/src/auth/magicLink/types.ts +137 -0
  82. package/src/config.ts +62 -0
  83. package/src/context.ts +252 -3
  84. package/src/generated/generated.ts +12302 -8878
  85. package/src/generic/ResolverBase.ts +35 -7
  86. package/src/index.ts +28 -0
  87. package/src/resolvers/CurrentUserContextResolver.ts +21 -5
  88. package/src/resolvers/EntityResolver.ts +17 -5
  89. package/src/resolvers/GenerateSeedTaxonomyResolver.ts +90 -0
  90. package/src/resolvers/RunClusterAnalysisResolver.ts +249 -0
  91. package/src/resolvers/UserResolver.ts +38 -2
  92. package/src/rest/SignatureWebhookHandler.ts +103 -0
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @fileoverview RS256 key manager for magic-link session JWTs.
3
+ *
4
+ * MJ signs magic-link session tokens with an RS256 private key and publishes the
5
+ * matching public key at a JWKS endpoint. Registering the `magic-link` auth
6
+ * provider with that JWKS URL lets MJServer's standard issuer-driven validation
7
+ * verify the tokens with no special-casing.
8
+ *
9
+ * @module @memberjunction/server/auth/magicLink
10
+ */
11
+
12
+ import { BaseSingleton } from '@memberjunction/global';
13
+ import { LogStatus } from '@memberjunction/core';
14
+ import { createPrivateKey, createPublicKey, generateKeyPairSync, createHash, type KeyObject } from 'node:crypto';
15
+ import jwt from 'jsonwebtoken';
16
+ import type { MagicLinkJWTClaims } from './types.js';
17
+
18
+ /** A single JSON Web Key plus the metadata jwks-rsa needs to match it. */
19
+ interface PublishedJWK extends JsonWebKey {
20
+ kid: string;
21
+ use: 'sig';
22
+ alg: 'RS256';
23
+ }
24
+
25
+ /**
26
+ * Manages the RS256 keypair used to sign and publish magic-link session tokens.
27
+ * Singleton so the keypair (and therefore the `kid`) is stable for the process
28
+ * lifetime — restarting with an ephemeral key invalidates outstanding sessions,
29
+ * which is the intended dev behavior and an acceptable production key-rotation
30
+ * mechanism.
31
+ */
32
+ export class MagicLinkKeyManager extends BaseSingleton<MagicLinkKeyManager> {
33
+ private privateKeyPem = '';
34
+ private publicKey?: KeyObject;
35
+ private _kid = '';
36
+ private _initialized = false;
37
+
38
+ // Public to satisfy BaseSingleton.getInstance's `this: new () => T` constraint
39
+ // (matches the AuthProviderFactory singleton pattern).
40
+ public constructor() {
41
+ super();
42
+ }
43
+
44
+ public static get Instance(): MagicLinkKeyManager {
45
+ return MagicLinkKeyManager.getInstance<MagicLinkKeyManager>();
46
+ }
47
+
48
+ public get IsInitialized(): boolean {
49
+ return this._initialized;
50
+ }
51
+
52
+ public get Kid(): string {
53
+ return this._kid;
54
+ }
55
+
56
+ /**
57
+ * Initializes the keypair from a provided PEM (raw or base64-encoded) or, if
58
+ * none is supplied, generates an ephemeral 2048-bit RSA keypair. Idempotent.
59
+ */
60
+ public Initialize(privateKeyPem?: string): void {
61
+ if (this._initialized) {
62
+ return;
63
+ }
64
+
65
+ let priv: KeyObject;
66
+ const supplied = privateKeyPem?.trim();
67
+ if (supplied) {
68
+ priv = createPrivateKey(this.normalizePem(supplied));
69
+ } else {
70
+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
71
+ priv = privateKey;
72
+ LogStatus(
73
+ '[MagicLink] No rsaPrivateKey configured — generated an EPHEMERAL RS256 keypair. ' +
74
+ 'Outstanding magic-link sessions will be invalidated on restart. Set magicLink.rsaPrivateKey ' +
75
+ '(or MJ_MAGIC_LINK_PRIVATE_KEY) for stable production keys.'
76
+ );
77
+ }
78
+
79
+ this.privateKeyPem = priv.export({ type: 'pkcs8', format: 'pem' }) as string;
80
+ this.publicKey = createPublicKey(priv);
81
+ this._kid = this.computeKid(this.publicKey);
82
+ this._initialized = true;
83
+ }
84
+
85
+ /**
86
+ * Signs a set of magic-link claims and returns the compact JWT.
87
+ * `iat`/`exp` are expected to already be set on the claims.
88
+ */
89
+ public Sign(claims: MagicLinkJWTClaims): string {
90
+ this.ensureInitialized();
91
+ return jwt.sign(claims, this.privateKeyPem, { algorithm: 'RS256', keyid: this._kid });
92
+ }
93
+
94
+ /**
95
+ * Returns the JWKS document (public key set) for the JWKS endpoint.
96
+ */
97
+ public GetJWKS(): { keys: PublishedJWK[] } {
98
+ this.ensureInitialized();
99
+ const jwk = this.publicKey!.export({ format: 'jwk' });
100
+ return { keys: [{ ...jwk, kid: this._kid, use: 'sig', alg: 'RS256' }] };
101
+ }
102
+
103
+ private ensureInitialized(): void {
104
+ if (!this._initialized) {
105
+ throw new Error('MagicLinkKeyManager not initialized — call Initialize() during server startup.');
106
+ }
107
+ }
108
+
109
+ /** Accepts raw PEM or base64-encoded PEM and returns raw PEM. */
110
+ private normalizePem(value: string): string {
111
+ if (value.includes('-----BEGIN')) {
112
+ return value;
113
+ }
114
+ return Buffer.from(value, 'base64').toString('utf8');
115
+ }
116
+
117
+ /** Stable key id derived from the public key (SHA-256 of DER, base64url, truncated). */
118
+ private computeKid(publicKey: KeyObject): string {
119
+ const pem = publicKey.export({ type: 'spki', format: 'pem' }) as string;
120
+ return createHash('sha256').update(pem).digest('base64url').slice(0, 16);
121
+ }
122
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * @fileoverview Express wiring + auth-provider registration for magic links.
3
+ *
4
+ * Mirrors the OAuth handler pattern: a public router (unauthenticated — JWKS +
5
+ * redeem) mounted BEFORE the unified auth middleware, and an authenticated
6
+ * router (invite creation) mounted AFTER it so `req.userPayload` is available.
7
+ *
8
+ * @module @memberjunction/server/auth/magicLink
9
+ */
10
+
11
+ import { Router, json, urlencoded, type Request, type Response } from 'express';
12
+ import { rateLimit } from 'express-rate-limit';
13
+ import { LogError, LogStatus, type AuthProviderConfig } from '@memberjunction/core';
14
+ import { AuthProviderFactory } from '@memberjunction/auth-providers';
15
+ import { configInfo, type MagicLinkConfig } from '../../config.js';
16
+ import { MagicLinkKeyManager } from './MagicLinkKeys.js';
17
+ import { MagicLinkService } from './MagicLinkService.js';
18
+ import { buildRedeemLandingHtml } from './redeemLanding.js';
19
+ import type { CreateMagicLinkInviteParams, RedeemMagicLinkResult } from './types.js';
20
+
21
+ /** The mount path for both routers (`/magic-link`). */
22
+ export const MAGIC_LINK_MOUNT_PATH = '/magic-link';
23
+
24
+ /** Path of the JWKS endpoint relative to the public URL. */
25
+ export const MAGIC_LINK_JWKS_PATH = `${MAGIC_LINK_MOUNT_PATH}/jwks.json`;
26
+
27
+ /**
28
+ * Builds the magic-link routers. The caller mounts `publicRouter` before the
29
+ * auth middleware and `authenticatedRouter` after it (both at MAGIC_LINK_MOUNT_PATH).
30
+ */
31
+ export function createMagicLinkHandler(publicUrl: string, config: MagicLinkConfig): {
32
+ publicRouter: Router;
33
+ authenticatedRouter: Router;
34
+ } {
35
+ // Initialize the signing keypair once.
36
+ MagicLinkKeyManager.Instance.Initialize(config.rsaPrivateKey);
37
+
38
+ const service = new MagicLinkService(publicUrl, config);
39
+
40
+ // Throttle the unauthenticated redemption endpoint and the authenticated
41
+ // create endpoint. /redeem is a public surface that does a DB lookup +
42
+ // (on a hit) user provisioning + token minting, so it must be rate-limited
43
+ // against guessing/enumeration/resource-exhaustion. Keyed by IP.
44
+ const redeemLimiter = rateLimit({
45
+ windowMs: config.rateLimitWindowMs,
46
+ limit: config.redeemRateLimitMax,
47
+ standardHeaders: 'draft-7',
48
+ legacyHeaders: false,
49
+ message: { success: false, errorCode: 'invalid', error: 'Too many redemption attempts. Try again later.' },
50
+ });
51
+ const createLimiter = rateLimit({
52
+ windowMs: config.rateLimitWindowMs,
53
+ limit: config.createRateLimitMax,
54
+ standardHeaders: 'draft-7',
55
+ legacyHeaders: false,
56
+ message: { success: false, error: 'Too many invite requests. Try again later.' },
57
+ });
58
+
59
+ // ── Public (unauthenticated) ──────────────────────────────────────────────
60
+ const publicRouter = Router();
61
+
62
+ publicRouter.get('/jwks.json', (_req: Request, res: Response) => {
63
+ res.status(200).json(MagicLinkKeyManager.Instance.GetJWKS());
64
+ });
65
+
66
+ // Sends a completed redemption result: browser flow → 302 into Explorer with
67
+ // the session token in the URL fragment (never sent to a server, so it stays
68
+ // out of access/proxy logs); API flow → JSON with an appropriate status.
69
+ const sendRedeemResult = (res: Response, result: RedeemMagicLinkResult, wantsJson: boolean): void => {
70
+ const explorerUrl = config.explorerUrl?.replace(/\/$/, '');
71
+ if (explorerUrl && !wantsJson) {
72
+ if (result.success && result.token) {
73
+ // Deep-link into the invited app's route (e.g. /app/data-explorer) rather
74
+ // than Explorer's root — root falls through to Explorer's default resource,
75
+ // which isn't the scoped app. Use the app's URL Path (what Explorer's
76
+ // GetAppByPath matches on); fall back to a name-slug only when Path is
77
+ // absent. Do NOT hand-roll a slug from the name when Path exists — the two
78
+ // can diverge and Explorer would fail to resolve the app.
79
+ const appSlug = result.applicationPath
80
+ ? result.applicationPath
81
+ : result.applicationName
82
+ ? result.applicationName.trim().toLowerCase().replace(/\s+/g, '-')
83
+ : '';
84
+ const path = appSlug ? `/app/${encodeURIComponent(appSlug)}` : '/';
85
+ res.redirect(302, `${explorerUrl}${path}#token=${encodeURIComponent(result.token)}`);
86
+ } else {
87
+ res.redirect(302, `${explorerUrl}/?mlError=${encodeURIComponent(result.errorCode ?? 'invalid')}`);
88
+ }
89
+ return;
90
+ }
91
+ // API/JSON flow.
92
+ // not_found / expired / consumed / revoked are client-side conditions (410 Gone);
93
+ // server_error / provisioning_failed are 500.
94
+ const status = result.success ? 200 : result.errorCode === 'server_error' || result.errorCode === 'provisioning_failed' ? 500 : 410;
95
+ res.status(status).json(result);
96
+ };
97
+
98
+ // GET /redeem is SAFE (no side effects). Link prefetchers and email security
99
+ // scanners routinely fetch URLs; a side-effectful GET would let them burn the
100
+ // single-use token before the human clicks. So GET renders an interstitial and
101
+ // the actual redemption happens only on POST (below), gated by a user click.
102
+ publicRouter.get('/redeem', redeemLimiter, (req: Request, res: Response) => {
103
+ const token = typeof req.query.token === 'string' ? req.query.token : '';
104
+ if (!token) {
105
+ res.status(400).json({ success: false, error: 'Missing token.' });
106
+ return;
107
+ }
108
+ // API callers must POST — GET never redeems.
109
+ if (req.query.format === 'json') {
110
+ res.status(405).json({ success: false, error: 'Redemption requires POST.', method: 'POST', path: `${MAGIC_LINK_MOUNT_PATH}/redeem` });
111
+ return;
112
+ }
113
+ res
114
+ .status(200)
115
+ .type('html')
116
+ .send(buildRedeemLandingHtml(token, `${MAGIC_LINK_MOUNT_PATH}/redeem`));
117
+ });
118
+
119
+ // POST /redeem performs the actual (side-effectful) redemption. Token arrives
120
+ // from the interstitial form body, an API client's JSON body, or the query.
121
+ publicRouter.post('/redeem', redeemLimiter, urlencoded({ extended: false }), json(), async (req: Request, res: Response) => {
122
+ const body = (req.body ?? {}) as { token?: string };
123
+ const token =
124
+ (typeof body.token === 'string' && body.token) ||
125
+ (typeof req.query.token === 'string' ? req.query.token : '');
126
+ const wantsJson = req.query.format === 'json' || req.is('application/json') === 'application/json';
127
+
128
+ if (!token) {
129
+ res.status(400).json({ success: false, error: 'Missing token.' });
130
+ return;
131
+ }
132
+
133
+ // Forensic context for the redemption audit trail. `req.ip` honors the app's
134
+ // trust-proxy setting; headers are best-effort and may be absent for API clients.
135
+ const result = await service.RedeemInvite(token, {
136
+ ipAddress: req.ip,
137
+ userAgent: req.get('user-agent') ?? undefined,
138
+ origin: req.get('origin') ?? undefined,
139
+ });
140
+ sendRedeemResult(res, result, wantsJson);
141
+ });
142
+
143
+ // ── Authenticated (invite creation) ───────────────────────────────────────
144
+ const authenticatedRouter = Router();
145
+
146
+ authenticatedRouter.post('/create', createLimiter, json(), async (req: Request, res: Response) => {
147
+ const creatingUser = req.userPayload?.userRecord;
148
+ if (!creatingUser) {
149
+ res.status(401).json({ success: false, error: 'Authentication required.' });
150
+ return;
151
+ }
152
+
153
+ const body = (req.body ?? {}) as Partial<CreateMagicLinkInviteParams>;
154
+ if (!body.email || !body.applicationId) {
155
+ res.status(400).json({ success: false, error: 'email and applicationId are required.' });
156
+ return;
157
+ }
158
+
159
+ const result = await service.CreateInvite(
160
+ {
161
+ email: body.email,
162
+ applicationId: body.applicationId,
163
+ roleId: body.roleId,
164
+ expiresInHours: body.expiresInHours,
165
+ maxUses: body.maxUses,
166
+ firstName: body.firstName,
167
+ lastName: body.lastName,
168
+ },
169
+ creatingUser,
170
+ );
171
+ // forbidden → 403 (caller not allowed to issue invites); invalid_role and
172
+ // other validation failures → 400.
173
+ const status = result.success ? 200 : result.errorCode === 'forbidden' ? 403 : 400;
174
+ res.status(status).json(result);
175
+ });
176
+
177
+ return { publicRouter, authenticatedRouter };
178
+ }
179
+
180
+ /**
181
+ * Registers the `magic-link` auth provider so MJServer's issuer-driven JWT
182
+ * validation accepts MJ-issued session tokens. Issuer = public URL, JWKS URL =
183
+ * the public JWKS endpoint, audience = configured magic-link audience.
184
+ *
185
+ * Also appends the provider to `configInfo.authProviders` so a later
186
+ * `initializeAuthProviders()` (which clears + repopulates from config) keeps it.
187
+ */
188
+ export function registerMagicLinkAuthProvider(publicUrl: string, config: MagicLinkConfig): void {
189
+ const base = publicUrl.replace(/\/$/, '');
190
+ const providerConfig: AuthProviderConfig = {
191
+ name: 'magic-link',
192
+ type: 'magic-link',
193
+ issuer: publicUrl,
194
+ audience: config.audience,
195
+ jwksUri: `${base}${MAGIC_LINK_JWKS_PATH}`,
196
+ };
197
+
198
+ try {
199
+ configInfo.authProviders = configInfo.authProviders ?? [];
200
+ if (!configInfo.authProviders.some((p) => p.type === 'magic-link')) {
201
+ configInfo.authProviders.push(providerConfig);
202
+ }
203
+ const factory = AuthProviderFactory.Instance;
204
+ factory.register(AuthProviderFactory.createProvider(providerConfig));
205
+ LogStatus(`[MagicLink] Registered auth provider (issuer: ${publicUrl}, jwks: ${providerConfig.jwksUri})`);
206
+ } catch (e) {
207
+ LogError(`[MagicLink] Failed to register auth provider: ${e instanceof Error ? e.message : String(e)}`);
208
+ }
209
+ }