Add OIDC provider for Outline wiki SSO
Add oidc-provider with MongoDB adapter so ghostguild.org can act as the identity provider for the self-hosted Outline wiki. Members authenticate via the existing magic-link flow, with automatic SSO when an active session exists. Includes interaction routes, well-known discovery endpoint, and login page.
This commit is contained in:
parent
a232a7bbf8
commit
8a529a8e7c
13 changed files with 1258 additions and 2 deletions
|
|
@ -7,6 +7,7 @@ const EXEMPT_PREFIXES = [
|
|||
'/api/helcim/webhook',
|
||||
'/api/slack/webhook',
|
||||
'/api/auth/verify',
|
||||
'/oidc/',
|
||||
]
|
||||
|
||||
function isExempt(path) {
|
||||
|
|
|
|||
24
server/routes/.well-known/openid-configuration.get.ts
Normal file
24
server/routes/.well-known/openid-configuration.get.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/**
|
||||
* Forward /.well-known/openid-configuration to the oidc-provider.
|
||||
*
|
||||
* The provider generates this discovery document automatically, but since the
|
||||
* catch-all route is mounted under /oidc/, requests to /.well-known/ need
|
||||
* explicit forwarding.
|
||||
*/
|
||||
import { getOidcProvider } from "../../utils/oidc-provider.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const provider = await getOidcProvider();
|
||||
const { req, res } = event.node;
|
||||
|
||||
// The provider expects the path relative to its root
|
||||
req.url = "/.well-known/openid-configuration";
|
||||
|
||||
const callback = provider.callback() as Function;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
callback(req, res, (err: unknown) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
30
server/routes/oidc/[...].ts
Normal file
30
server/routes/oidc/[...].ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/**
|
||||
* Catch-all route that delegates all /oidc/* requests to the oidc-provider.
|
||||
*
|
||||
* This exposes the standard OIDC endpoints:
|
||||
* /oidc/auth — authorization
|
||||
* /oidc/token — token exchange
|
||||
* /oidc/me — userinfo
|
||||
* /oidc/session/end — logout
|
||||
* /oidc/jwks — JSON Web Key Set
|
||||
*/
|
||||
import { getOidcProvider } from "../../utils/oidc-provider.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const provider = await getOidcProvider();
|
||||
const { req, res } = event.node;
|
||||
|
||||
// oidc-provider expects paths relative to its own mount point.
|
||||
// Nitro gives us the full path, so strip the /oidc prefix.
|
||||
const originalUrl = req.url || "";
|
||||
req.url = originalUrl.replace(/^\/oidc/, "") || "/";
|
||||
|
||||
// Hand off to oidc-provider's Connect-style callback
|
||||
const callback = provider.callback() as Function;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
callback(req, res, (err: unknown) => {
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
94
server/routes/oidc/interaction/[uid].get.ts
Normal file
94
server/routes/oidc/interaction/[uid].get.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* OIDC interaction handler — checks for an existing Ghost Guild session.
|
||||
*
|
||||
* Flow:
|
||||
* 1. Outline redirects user to /oidc/auth
|
||||
* 2. oidc-provider creates an interaction and redirects here
|
||||
* 3. If the user has a valid auth-token cookie → complete the interaction (SSO)
|
||||
* 4. Otherwise → redirect to the OIDC login page
|
||||
*/
|
||||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../../models/member.js";
|
||||
import { connectDB } from "../../../utils/mongoose.js";
|
||||
import { getOidcProvider } from "../../../utils/oidc-provider.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const provider = await getOidcProvider();
|
||||
const uid = getRouterParam(event, "uid")!;
|
||||
|
||||
// Load the interaction details from oidc-provider
|
||||
const interactionDetails = await provider.interactionDetails(
|
||||
event.node.req,
|
||||
event.node.res
|
||||
);
|
||||
const { prompt } = interactionDetails;
|
||||
|
||||
// ----- Login prompt -----
|
||||
if (prompt.name === "login") {
|
||||
// Check for existing Ghost Guild session
|
||||
const token = getCookie(event, "auth-token");
|
||||
|
||||
if (token) {
|
||||
try {
|
||||
const config = useRuntimeConfig();
|
||||
const decoded = jwt.verify(token, config.jwtSecret) as {
|
||||
memberId: string;
|
||||
};
|
||||
|
||||
await connectDB();
|
||||
const member = await (Member as any).findById(decoded.memberId);
|
||||
|
||||
if (
|
||||
member &&
|
||||
member.status !== "suspended" &&
|
||||
member.status !== "cancelled"
|
||||
) {
|
||||
// Auto-complete the login interaction (SSO)
|
||||
const result = {
|
||||
login: { accountId: member._id.toString() },
|
||||
};
|
||||
await provider.interactionFinished(
|
||||
event.node.req,
|
||||
event.node.res,
|
||||
result,
|
||||
{ mergeWithLastSubmission: false }
|
||||
);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Token invalid — fall through to login page
|
||||
}
|
||||
}
|
||||
|
||||
// No valid session — redirect to login page
|
||||
return sendRedirect(event, `/oidc/login?uid=${uid}`, 302);
|
||||
}
|
||||
|
||||
// ----- Consent prompt -----
|
||||
if (prompt.name === "consent") {
|
||||
// Auto-approve consent for our first-party client
|
||||
const grant = interactionDetails.grantId
|
||||
? await provider.Grant.find(interactionDetails.grantId)
|
||||
: new provider.Grant({
|
||||
accountId: interactionDetails.session!.accountId,
|
||||
clientId: interactionDetails.params.client_id as string,
|
||||
});
|
||||
|
||||
if (grant) {
|
||||
grant.addOIDCScope("openid profile email");
|
||||
await grant.save();
|
||||
|
||||
const result = { consent: { grantId: grant.jti } };
|
||||
await provider.interactionFinished(
|
||||
event.node.req,
|
||||
event.node.res,
|
||||
result,
|
||||
{ mergeWithLastSubmission: true }
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback — shouldn't reach here normally
|
||||
throw createError({ statusCode: 400, statusMessage: "Unknown interaction" });
|
||||
});
|
||||
81
server/routes/oidc/interaction/login.post.ts
Normal file
81
server/routes/oidc/interaction/login.post.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/**
|
||||
* Handle magic link login request during OIDC interaction flow.
|
||||
*
|
||||
* POST /oidc/interaction/login
|
||||
* Body: { email: string, uid: string }
|
||||
*
|
||||
* Sends a magic link email. The link includes the OIDC interaction uid so the
|
||||
* verify step can complete the interaction after authenticating.
|
||||
*/
|
||||
import jwt from "jsonwebtoken";
|
||||
import { Resend } from "resend";
|
||||
import Member from "../../../models/member.js";
|
||||
import { connectDB } from "../../../utils/mongoose.js";
|
||||
|
||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
await connectDB();
|
||||
|
||||
const body = await readBody(event);
|
||||
const email = body?.email?.trim()?.toLowerCase();
|
||||
const uid = body?.uid;
|
||||
|
||||
if (!email || !uid) {
|
||||
throw createError({
|
||||
statusCode: 400,
|
||||
statusMessage: "Email and interaction uid are required",
|
||||
});
|
||||
}
|
||||
|
||||
const GENERIC_MESSAGE =
|
||||
"If this email is registered, we've sent a login link.";
|
||||
|
||||
const member = await (Member as any).findOne({ email });
|
||||
if (!member) {
|
||||
return { success: true, message: GENERIC_MESSAGE };
|
||||
}
|
||||
|
||||
const config = useRuntimeConfig(event);
|
||||
const token = jwt.sign(
|
||||
{ memberId: member._id, oidcUid: uid },
|
||||
config.jwtSecret,
|
||||
{ expiresIn: "15m" }
|
||||
);
|
||||
|
||||
const headers = getHeaders(event);
|
||||
const baseUrl =
|
||||
process.env.BASE_URL ||
|
||||
`${headers.host?.includes("localhost") ? "http" : "https"}://${headers.host}`;
|
||||
|
||||
try {
|
||||
await resend.emails.send({
|
||||
from: "Ghost Guild <ghostguild@babyghosts.org>",
|
||||
to: email,
|
||||
subject: "Sign in to Ghost Guild Wiki",
|
||||
html: `
|
||||
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
|
||||
<h2 style="color: #2563eb;">Sign in to the Ghost Guild Wiki</h2>
|
||||
<p>Click the button below to sign in:</p>
|
||||
<div style="text-align: center; margin: 30px 0;">
|
||||
<a href="${baseUrl}/oidc/interaction/verify?token=${token}"
|
||||
style="background-color: #2563eb; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; display: inline-block;">
|
||||
Sign In
|
||||
</a>
|
||||
</div>
|
||||
<p style="color: #666; font-size: 14px;">
|
||||
This link expires in 15 minutes. If you didn't request this, you can safely ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
|
||||
return { success: true, message: GENERIC_MESSAGE };
|
||||
} catch (error) {
|
||||
console.error("Failed to send OIDC login email:", error);
|
||||
throw createError({
|
||||
statusCode: 500,
|
||||
statusMessage: "Failed to send login email. Please try again.",
|
||||
});
|
||||
}
|
||||
});
|
||||
75
server/routes/oidc/interaction/verify.get.ts
Normal file
75
server/routes/oidc/interaction/verify.get.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
/**
|
||||
* Verify magic link token and complete the OIDC login interaction.
|
||||
*
|
||||
* GET /oidc/interaction/verify?token=...
|
||||
*
|
||||
* This is the endpoint the magic link email points to. It:
|
||||
* 1. Verifies the JWT token
|
||||
* 2. Sets the Ghost Guild session cookie (so future logins are SSO)
|
||||
* 3. Completes the OIDC interaction so the user is redirected back to Outline
|
||||
*/
|
||||
import jwt from "jsonwebtoken";
|
||||
import Member from "../../../models/member.js";
|
||||
import { connectDB } from "../../../utils/mongoose.js";
|
||||
import { getOidcProvider } from "../../../utils/oidc-provider.js";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { token } = getQuery(event);
|
||||
|
||||
if (!token) {
|
||||
throw createError({ statusCode: 400, statusMessage: "Token is required" });
|
||||
}
|
||||
|
||||
const config = useRuntimeConfig(event);
|
||||
|
||||
let decoded: { memberId: string; oidcUid: string };
|
||||
try {
|
||||
decoded = jwt.verify(token as string, config.jwtSecret) as typeof decoded;
|
||||
} catch {
|
||||
throw createError({
|
||||
statusCode: 401,
|
||||
statusMessage: "Invalid or expired token",
|
||||
});
|
||||
}
|
||||
|
||||
await connectDB();
|
||||
const member = await (Member as any).findById(decoded.memberId);
|
||||
|
||||
if (!member) {
|
||||
throw createError({ statusCode: 404, statusMessage: "Member not found" });
|
||||
}
|
||||
|
||||
if (member.status === "suspended" || member.status === "cancelled") {
|
||||
throw createError({
|
||||
statusCode: 403,
|
||||
statusMessage: `Account is ${member.status}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Set Ghost Guild session cookie for future SSO
|
||||
const sessionToken = jwt.sign(
|
||||
{ memberId: member._id, email: member.email },
|
||||
config.jwtSecret,
|
||||
{ expiresIn: "7d" }
|
||||
);
|
||||
|
||||
setCookie(event, "auth-token", sessionToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "lax",
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
|
||||
// Complete the OIDC interaction
|
||||
const provider = await getOidcProvider();
|
||||
const result = {
|
||||
login: { accountId: member._id.toString() },
|
||||
};
|
||||
|
||||
await provider.interactionFinished(
|
||||
event.node.req,
|
||||
event.node.res,
|
||||
result,
|
||||
{ mergeWithLastSubmission: false }
|
||||
);
|
||||
});
|
||||
114
server/utils/oidc-mongodb-adapter.ts
Normal file
114
server/utils/oidc-mongodb-adapter.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
/**
|
||||
* MongoDB adapter for oidc-provider.
|
||||
*
|
||||
* Stores OIDC tokens, sessions, and grants in an `oidc_payloads` collection
|
||||
* with TTL indexes for automatic cleanup. Uses the existing Mongoose connection.
|
||||
*/
|
||||
import mongoose from "mongoose";
|
||||
import { connectDB } from "./mongoose.js";
|
||||
|
||||
const collectionName = "oidc_payloads";
|
||||
|
||||
type MongoPayload = {
|
||||
_id: string;
|
||||
payload: Record<string, unknown>;
|
||||
expiresAt?: Date;
|
||||
userCode?: string;
|
||||
uid?: string;
|
||||
grantId?: string;
|
||||
};
|
||||
|
||||
let collectionReady = false;
|
||||
|
||||
async function getCollection() {
|
||||
await connectDB();
|
||||
const db = mongoose.connection.db!;
|
||||
const col = db.collection<MongoPayload>(collectionName);
|
||||
|
||||
if (!collectionReady) {
|
||||
// TTL index — MongoDB automatically removes documents after expiresAt
|
||||
await col
|
||||
.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
|
||||
.catch(() => {});
|
||||
// Lookup indexes
|
||||
await col.createIndex({ "payload.grantId": 1 }).catch(() => {});
|
||||
await col.createIndex({ "payload.userCode": 1 }).catch(() => {});
|
||||
await col.createIndex({ "payload.uid": 1 }).catch(() => {});
|
||||
collectionReady = true;
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
function prefixedId(model: string, id: string) {
|
||||
return `${model}:${id}`;
|
||||
}
|
||||
|
||||
export class MongoAdapter {
|
||||
model: string;
|
||||
|
||||
constructor(model: string) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
async upsert(
|
||||
id: string,
|
||||
payload: Record<string, unknown>,
|
||||
expiresIn: number
|
||||
) {
|
||||
const col = await getCollection();
|
||||
const expiresAt = expiresIn
|
||||
? new Date(Date.now() + expiresIn * 1000)
|
||||
: undefined;
|
||||
|
||||
await col.updateOne(
|
||||
{ _id: prefixedId(this.model, id) as any },
|
||||
{
|
||||
$set: {
|
||||
payload,
|
||||
...(expiresAt ? { expiresAt } : {}),
|
||||
},
|
||||
},
|
||||
{ upsert: true }
|
||||
);
|
||||
}
|
||||
|
||||
async find(id: string) {
|
||||
const col = await getCollection();
|
||||
const doc = await col.findOne({ _id: prefixedId(this.model, id) as any });
|
||||
if (!doc) return undefined;
|
||||
return doc.payload;
|
||||
}
|
||||
|
||||
async findByUserCode(userCode: string) {
|
||||
const col = await getCollection();
|
||||
const doc = await col.findOne({ "payload.userCode": userCode });
|
||||
if (!doc) return undefined;
|
||||
return doc.payload;
|
||||
}
|
||||
|
||||
async findByUid(uid: string) {
|
||||
const col = await getCollection();
|
||||
const doc = await col.findOne({ "payload.uid": uid });
|
||||
if (!doc) return undefined;
|
||||
return doc.payload;
|
||||
}
|
||||
|
||||
async consume(id: string) {
|
||||
const col = await getCollection();
|
||||
await col.updateOne(
|
||||
{ _id: prefixedId(this.model, id) as any },
|
||||
{ $set: { "payload.consumed": Math.floor(Date.now() / 1000) } }
|
||||
);
|
||||
}
|
||||
|
||||
async destroy(id: string) {
|
||||
const col = await getCollection();
|
||||
await col.deleteOne({ _id: prefixedId(this.model, id) as any });
|
||||
}
|
||||
|
||||
async revokeByGrantId(grantId: string) {
|
||||
const col = await getCollection();
|
||||
await col.deleteMany({ "payload.grantId": grantId });
|
||||
}
|
||||
}
|
||||
117
server/utils/oidc-provider.ts
Normal file
117
server/utils/oidc-provider.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
/**
|
||||
* OIDC Provider configuration for Ghost Guild.
|
||||
*
|
||||
* ghostguild.org acts as the identity provider. Outline wiki is the sole
|
||||
* relying party (client). Members authenticate via the existing magic-link
|
||||
* flow, and the provider issues standard OIDC tokens so Outline can identify
|
||||
* them.
|
||||
*/
|
||||
import Provider from "oidc-provider";
|
||||
import { MongoAdapter } from "./oidc-mongodb-adapter.js";
|
||||
import Member from "../models/member.js";
|
||||
import { connectDB } from "./mongoose.js";
|
||||
|
||||
let _provider: InstanceType<typeof Provider> | null = null;
|
||||
|
||||
export async function getOidcProvider() {
|
||||
if (_provider) return _provider;
|
||||
|
||||
const config = useRuntimeConfig();
|
||||
const issuer =
|
||||
process.env.OIDC_ISSUER || config.public.appUrl || "https://ghostguild.org";
|
||||
|
||||
_provider = new Provider(issuer, {
|
||||
adapter: MongoAdapter,
|
||||
|
||||
clients: [
|
||||
{
|
||||
client_id: process.env.OIDC_CLIENT_ID || "outline-wiki",
|
||||
client_secret: process.env.OIDC_CLIENT_SECRET || "",
|
||||
redirect_uris: [
|
||||
"https://wiki.ghostguild.org/auth/oidc.callback",
|
||||
// Local development callback
|
||||
"http://localhost:3100/auth/oidc.callback",
|
||||
],
|
||||
post_logout_redirect_uris: [
|
||||
"https://wiki.ghostguild.org",
|
||||
"http://localhost:3100",
|
||||
],
|
||||
grant_types: ["authorization_code", "refresh_token"],
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "client_secret_post",
|
||||
},
|
||||
],
|
||||
|
||||
claims: {
|
||||
openid: ["sub"],
|
||||
profile: ["name", "preferred_username"],
|
||||
email: ["email", "email_verified"],
|
||||
},
|
||||
|
||||
scopes: ["openid", "profile", "email", "offline_access"],
|
||||
|
||||
findAccount: async (_ctx: unknown, id: string) => {
|
||||
await connectDB();
|
||||
const member = await (Member as any).findById(id);
|
||||
if (!member) return undefined;
|
||||
|
||||
return {
|
||||
accountId: id,
|
||||
async claims(_use: string, _scope: string) {
|
||||
return {
|
||||
sub: id,
|
||||
name: member.name,
|
||||
preferred_username: member.name,
|
||||
email: member.email,
|
||||
email_verified: true,
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
cookies: {
|
||||
keys: (process.env.OIDC_COOKIE_SECRET || "dev-cookie-secret").split(","),
|
||||
},
|
||||
|
||||
ttl: {
|
||||
AccessToken: 3600, // 1 hour
|
||||
AuthorizationCode: 600, // 10 minutes
|
||||
RefreshToken: 14 * 24 * 60 * 60, // 14 days
|
||||
Session: 14 * 24 * 60 * 60, // 14 days
|
||||
Interaction: 600, // 10 minutes
|
||||
Grant: 14 * 24 * 60 * 60, // 14 days
|
||||
},
|
||||
|
||||
features: {
|
||||
devInteractions: {
|
||||
enabled: process.env.NODE_ENV !== "production",
|
||||
},
|
||||
revocation: { enabled: true },
|
||||
rpInitiatedLogout: { enabled: true },
|
||||
},
|
||||
|
||||
interactions: {
|
||||
url(_ctx: unknown, interaction: { uid: string }) {
|
||||
return `/oidc/interaction/${interaction.uid}`;
|
||||
},
|
||||
},
|
||||
|
||||
// Allow Outline to use PKCE but don't require it
|
||||
pkce: {
|
||||
required: () => false,
|
||||
},
|
||||
|
||||
// Skip consent for our first-party Outline client
|
||||
loadExistingGrant: async (ctx: any) => {
|
||||
const grant = new (ctx.oidc.provider.Grant as any)({
|
||||
accountId: ctx.oidc.session!.accountId,
|
||||
clientId: ctx.oidc.client!.clientId,
|
||||
});
|
||||
grant.addOIDCScope("openid profile email");
|
||||
await grant.save();
|
||||
return grant;
|
||||
},
|
||||
});
|
||||
|
||||
return _provider;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue