@plasgos/auth-verify 0.0.0-stage → 0.1.0-next.3
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.
- package/CHANGELOG.md +27 -0
- package/LICENSE +15 -0
- package/README.md +122 -2
- package/THIRD_PARTY_NOTICES.md +31 -0
- package/dist/express.cjs +157 -0
- package/dist/express.cjs.map +1 -0
- package/dist/express.d.cts +90 -0
- package/dist/express.d.ts +90 -0
- package/dist/express.js +127 -0
- package/dist/express.js.map +1 -0
- package/dist/index.cjs +1254 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +67 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.js +499 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs.cjs +1395 -0
- package/dist/nestjs.cjs.map +1 -0
- package/dist/nestjs.d.cts +153 -0
- package/dist/nestjs.d.ts +153 -0
- package/dist/nestjs.js +637 -0
- package/dist/nestjs.js.map +1 -0
- package/dist/types-CGtRnj59.d.cts +193 -0
- package/dist/types-CGtRnj59.d.ts +193 -0
- package/dist/webhook.cjs +296 -0
- package/dist/webhook.cjs.map +1 -0
- package/dist/webhook.d.cts +196 -0
- package/dist/webhook.d.ts +196 -0
- package/dist/webhook.js +265 -0
- package/dist/webhook.js.map +1 -0
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +98 -0
- package/docs/contoh-hitungcuan.md +255 -0
- package/docs/contoh-plaslink.md +244 -0
- package/docs/error.md +613 -0
- package/docs/examples/auth-verify-readme.ts +42 -0
- package/docs/examples/bff-express.ts +370 -0
- package/docs/examples/bff-proxy.ts +335 -0
- package/docs/examples/bff-redis-lock.ts +187 -0
- package/docs/examples/bff-revocation.ts +136 -0
- package/docs/examples/config-error.ts +24 -0
- package/docs/examples/env.ts +150 -0
- package/docs/examples/failure-log.ts +18 -0
- package/docs/examples/login-client.ts +46 -0
- package/docs/examples/login-flow.ts +186 -0
- package/docs/examples/plaslink-connect.ts +48 -0
- package/docs/examples/readme.ts +60 -0
- package/docs/examples/service-client.ts +105 -0
- package/docs/examples/session-store.ts +53 -0
- package/docs/examples/token-commonjs.cjs +95 -0
- package/docs/examples/token-express.ts +56 -0
- package/docs/examples/token-fetch.ts +24 -0
- package/docs/examples/token-nestjs-jest.ts +77 -0
- package/docs/examples/token-nestjs.ts +127 -0
- package/docs/examples/token-socket.ts +59 -0
- package/docs/examples/token-testing.ts +100 -0
- package/docs/examples/token-verifier.ts +132 -0
- package/docs/examples/user-events.ts +110 -0
- package/docs/examples/webhook-express.ts +46 -0
- package/docs/examples/webhook-fetch.ts +60 -0
- package/docs/examples/webhook-nestjs.ts +59 -0
- package/docs/examples/webhook-testing.ts +60 -0
- package/docs/examples/webhook-verifier.ts +197 -0
- package/docs/login-web.md +650 -0
- package/docs/memulai.md +419 -0
- package/docs/server-ke-server.md +287 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +810 -0
- package/package.json +101 -3
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// #region commonjs
|
|
2
|
+
"use strict";
|
|
3
|
+
// CommonJS JavaScript (no "type" in package.json, plain require), Express 4 or 5.
|
|
4
|
+
const express = require("express");
|
|
5
|
+
const { createAccessTokenVerifier } = require("@plasgos/auth-verify");
|
|
6
|
+
const { principalOf, requirePlasgosToken } = require("@plasgos/auth-verify/express");
|
|
7
|
+
|
|
8
|
+
/** @param {string} name */
|
|
9
|
+
function requiredEnv(name) {
|
|
10
|
+
const value = process.env[name];
|
|
11
|
+
if (value === undefined || value.trim() === "") throw new Error(`${name} is not set`);
|
|
12
|
+
return value.trim();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** @returns {"sandbox" | "production"} */
|
|
16
|
+
function readEnvironment() {
|
|
17
|
+
const value = requiredEnv("PLASGOS_ENV");
|
|
18
|
+
if (value !== "sandbox" && value !== "production") throw new Error('PLASGOS_ENV must be "sandbox" or "production"');
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Thrown when the marker store cannot be read; the error handler answers 503. */
|
|
23
|
+
class RevocationStoreUnavailableError extends Error {}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The marker check of verifikasi-token.md §8 in JavaScript: a revoked session, a blocked user, or a
|
|
27
|
+
* credential version above the token's cv refuses the token. A store error is thrown, never "false".
|
|
28
|
+
* @param {{ get(key: string): Promise<string | null> }} store an ioredis client fits it
|
|
29
|
+
* @returns {(principal: import("@plasgos/auth-verify").UserAccessPrincipal) => Promise<boolean>}
|
|
30
|
+
*/
|
|
31
|
+
function revocationCheck(store) {
|
|
32
|
+
return async (principal) => {
|
|
33
|
+
const publicId = principal.claims.plasgos_public_id;
|
|
34
|
+
const tokenVersion = principal.credentialVersion;
|
|
35
|
+
if (publicId === undefined || tokenVersion === null) return true;
|
|
36
|
+
/** @type {(string | null)[]} */
|
|
37
|
+
let markers;
|
|
38
|
+
try {
|
|
39
|
+
markers = await Promise.all([
|
|
40
|
+
store.get(`myapp:revocation:sid:${principal.sessionId}`),
|
|
41
|
+
store.get(`myapp:revocation:blocked:${publicId}`),
|
|
42
|
+
store.get(`myapp:revocation:cv:${publicId}`),
|
|
43
|
+
]);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
throw new RevocationStoreUnavailableError("revocation store unavailable", { cause: error });
|
|
46
|
+
}
|
|
47
|
+
const [revokedSession, blocked, storedVersion] = markers;
|
|
48
|
+
if (revokedSession !== null || blocked !== null) return true;
|
|
49
|
+
if (storedVersion === null || storedVersion === undefined) return false;
|
|
50
|
+
const stored = Number(storedVersion);
|
|
51
|
+
if (!Number.isSafeInteger(stored)) throw new RevocationStoreUnavailableError("revocation store unavailable");
|
|
52
|
+
return stored > tokenVersion;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The app with one protected route. Create it once at start: a wrong option throws one ConfigError.
|
|
58
|
+
* @param {{ get(key: string): Promise<string | null> }} store
|
|
59
|
+
* @returns {import("express").Express}
|
|
60
|
+
*/
|
|
61
|
+
function createCrmApp(store) {
|
|
62
|
+
const verifier = createAccessTokenVerifier({
|
|
63
|
+
environment: readEnvironment(),
|
|
64
|
+
issuer: requiredEnv("PLASGOS_ISSUER"),
|
|
65
|
+
audience: requiredEnv("PLASGOS_TOKEN_AUDIENCE"),
|
|
66
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
67
|
+
isRevoked: revocationCheck(store),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
const app = express();
|
|
71
|
+
const requireToken = requirePlasgosToken(verifier, { scopes: ["crm:access"], requireClaims: ["plasgos_public_id", "cv"] });
|
|
72
|
+
|
|
73
|
+
app.get("/v2/crm/contacts", requireToken, (req, res) => {
|
|
74
|
+
res.json({ owner: principalOf(req).claims.plasgos_public_id, contacts: [] });
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
/** @type {import("express").ErrorRequestHandler} */
|
|
78
|
+
const apiErrors = (error, _req, res, next) => {
|
|
79
|
+
if (res.headersSent) {
|
|
80
|
+
next(error);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (error instanceof RevocationStoreUnavailableError) {
|
|
84
|
+
res.setHeader("Retry-After", "5");
|
|
85
|
+
res.status(503).json({ error: "temporarily_unavailable" });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
res.status(500).json({ error: "internal_error" });
|
|
89
|
+
};
|
|
90
|
+
app.use(apiErrors);
|
|
91
|
+
return app;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { createCrmApp, revocationCheck };
|
|
95
|
+
// #endregion commonjs
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { AccessTokenVerifier } from "@plasgos/auth-verify";
|
|
2
|
+
import { principalOf, requirePlasgosToken } from "@plasgos/auth-verify/express";
|
|
3
|
+
import express from "express";
|
|
4
|
+
import type { Express, NextFunction, Request, Response } from "express";
|
|
5
|
+
|
|
6
|
+
import { RevocationStoreUnavailableError, callerOf } from "./token-verifier.js";
|
|
7
|
+
|
|
8
|
+
// #region errors
|
|
9
|
+
/**
|
|
10
|
+
* The app's error handler, registered after the routes. A token the SDK refuses never gets here: the
|
|
11
|
+
* middleware answers 401, 403 or 503 itself. What gets here is the app's own errors, for example the
|
|
12
|
+
* marker store being down inside isRevoked: 503, because the token itself may be fine.
|
|
13
|
+
*/
|
|
14
|
+
function apiErrors(error: unknown, _req: Request, res: Response, next: NextFunction): void {
|
|
15
|
+
if (res.headersSent) {
|
|
16
|
+
next(error);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (error instanceof RevocationStoreUnavailableError) {
|
|
20
|
+
res.setHeader("Retry-After", "5");
|
|
21
|
+
res.status(503).json({ error: "temporarily_unavailable" });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
res.status(500).json({ error: "internal_error" });
|
|
25
|
+
}
|
|
26
|
+
// #endregion errors
|
|
27
|
+
|
|
28
|
+
// #region app
|
|
29
|
+
/** The verifier comes from createApiTokenVerifier, created once at start. Tests pass their own. */
|
|
30
|
+
export function createApp(verifier: AccessTokenVerifier): Express {
|
|
31
|
+
const app = express();
|
|
32
|
+
app.use(express.json({ limit: "100kb" }));
|
|
33
|
+
|
|
34
|
+
// Created once, used by many routes. The requirements are checked here: a wrong one throws TypeError.
|
|
35
|
+
// requireClaims repeats the verifier's list: harmless, and the routes stay safe if the verifier changes.
|
|
36
|
+
const requireToken = requirePlasgosToken(verifier, {
|
|
37
|
+
scopes: ["crm:access"],
|
|
38
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
39
|
+
});
|
|
40
|
+
// A sensitive action also needs a login of at most 10 minutes ago (else 401 with max_age=600).
|
|
41
|
+
const requireRecentLogin = requirePlasgosToken(verifier, { scopes: ["crm:access"], maxAuthAge: 600 });
|
|
42
|
+
|
|
43
|
+
app.get("/api/contacts", requireToken, (req, res) => {
|
|
44
|
+
const caller = callerOf(principalOf(req));
|
|
45
|
+
res.json({ owner: caller.publicId, contacts: [] });
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
app.post("/api/contacts/export", requireRecentLogin, (req, res) => {
|
|
49
|
+
const caller = callerOf(principalOf(req));
|
|
50
|
+
res.status(202).json({ owner: caller.publicId, queued: true });
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
app.use(apiErrors);
|
|
54
|
+
return app;
|
|
55
|
+
}
|
|
56
|
+
// #endregion app
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { AuthVerifyError, authErrorResponse } from "@plasgos/auth-verify";
|
|
2
|
+
import type { AccessTokenVerifier, UserAccessPrincipal } from "@plasgos/auth-verify";
|
|
3
|
+
|
|
4
|
+
import { RevocationStoreUnavailableError, callerOf } from "./token-verifier.js";
|
|
5
|
+
|
|
6
|
+
// #region route
|
|
7
|
+
/** GET /api/contacts in a server built on Request and Response (React Router, Hono, route handlers). */
|
|
8
|
+
export async function contactsRoute(request: Request, verifier: AccessTokenVerifier): Promise<Response> {
|
|
9
|
+
let principal: UserAccessPrincipal;
|
|
10
|
+
try {
|
|
11
|
+
// verifyRequest reads Authorization, and X-Request-Id for the onReject event.
|
|
12
|
+
principal = await verifier.verifyRequest(request, { scopes: ["crm:access"] });
|
|
13
|
+
} catch (error) {
|
|
14
|
+
// A refused token: 401, 403 or 503 with the right WWW-Authenticate header and a JSON body.
|
|
15
|
+
if (error instanceof AuthVerifyError) return authErrorResponse(error);
|
|
16
|
+
// isRevoked could not read its store: fail closed, without a 401 that sends the client to login.
|
|
17
|
+
if (error instanceof RevocationStoreUnavailableError) {
|
|
18
|
+
return Response.json({ error: "temporarily_unavailable" }, { status: 503, headers: { "Retry-After": "5" } });
|
|
19
|
+
}
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
return Response.json({ owner: callerOf(principal).publicId, contacts: [] });
|
|
23
|
+
}
|
|
24
|
+
// #endregion route
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
|
|
3
|
+
import type { Server } from "node:http";
|
|
4
|
+
|
|
5
|
+
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
|
|
6
|
+
import type { INestApplication } from "@nestjs/common";
|
|
7
|
+
import { APP_FILTER } from "@nestjs/core";
|
|
8
|
+
import { Test } from "@nestjs/testing";
|
|
9
|
+
import { PlasgosAuthModule } from "@plasgos/auth-verify/nestjs";
|
|
10
|
+
import request from "supertest";
|
|
11
|
+
|
|
12
|
+
import { ContactsController, RevocationStoreUnavailableFilter } from "./token-nestjs.js";
|
|
13
|
+
import { TEST_AUDIENCE, TEST_ISSUER, createTestSigner, memoryRevocationStore, testClaims } from "./token-testing.js";
|
|
14
|
+
import { revocationCheck, revocationKeys } from "./token-verifier.js";
|
|
15
|
+
|
|
16
|
+
// #region jest
|
|
17
|
+
describe("GET /api/contacts", () => {
|
|
18
|
+
const signer = createTestSigner();
|
|
19
|
+
// usr-test-0002 changed its password: tokens with cv below 2 are revoked.
|
|
20
|
+
const store = memoryRevocationStore({ [revocationKeys.credentialVersion("usr-test-0002")]: "2" });
|
|
21
|
+
let app: INestApplication;
|
|
22
|
+
let server: Server;
|
|
23
|
+
|
|
24
|
+
beforeAll(async () => {
|
|
25
|
+
const moduleRef = await Test.createTestingModule({
|
|
26
|
+
imports: [
|
|
27
|
+
// The production options, with the test key instead of the JWKS request (sandbox only).
|
|
28
|
+
PlasgosAuthModule.forRoot({
|
|
29
|
+
environment: "sandbox",
|
|
30
|
+
issuer: TEST_ISSUER,
|
|
31
|
+
audience: TEST_AUDIENCE,
|
|
32
|
+
jwks: signer.jwks,
|
|
33
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
34
|
+
isRevoked: revocationCheck(store),
|
|
35
|
+
}),
|
|
36
|
+
],
|
|
37
|
+
controllers: [ContactsController],
|
|
38
|
+
providers: [{ provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter }],
|
|
39
|
+
}).compile();
|
|
40
|
+
app = moduleRef.createNestApplication();
|
|
41
|
+
await app.init();
|
|
42
|
+
server = app.getHttpServer() as Server;
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
afterAll(async () => {
|
|
46
|
+
await app.close();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const get = (token?: string) => {
|
|
50
|
+
const call = request(server).get("/api/contacts");
|
|
51
|
+
return token === undefined ? call : call.set("Authorization", `Bearer ${token}`);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
it("401 without a token", async () => {
|
|
55
|
+
const res = await get();
|
|
56
|
+
expect(res.status).toBe(401);
|
|
57
|
+
expect(res.get("WWW-Authenticate")).toBe("Bearer");
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("200 with a good token", async () => {
|
|
61
|
+
const res = await get(signer.sign(testClaims()));
|
|
62
|
+
expect(res.status).toBe(200);
|
|
63
|
+
expect(res.text).toBe('{"owner":"usr-test-0001","contacts":[]}');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it("403 without the scope", async () => {
|
|
67
|
+
const res = await get(signer.sign(testClaims({ scope: "openid" })));
|
|
68
|
+
expect(res.status).toBe(403);
|
|
69
|
+
expect(res.get("WWW-Authenticate")).toBe('Bearer error="insufficient_scope", scope="crm:access"');
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it("401 when the credential version went up after the token was issued", async () => {
|
|
73
|
+
const res = await get(signer.sign(testClaims({ plasgos_public_id: "usr-test-0002", cv: 1 })));
|
|
74
|
+
expect(res.status).toBe(401);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
// #endregion jest
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { Catch, Controller, Get, HttpCode, Module, Post, UseGuards } from "@nestjs/common";
|
|
2
|
+
import type { ArgumentsHost, DynamicModule, ExceptionFilter } from "@nestjs/common";
|
|
3
|
+
import { APP_FILTER, APP_GUARD } from "@nestjs/core";
|
|
4
|
+
import {
|
|
5
|
+
PlasgosAccessTokenGuard,
|
|
6
|
+
PlasgosAuthModule,
|
|
7
|
+
PlasgosPrincipal,
|
|
8
|
+
RequireRecentAuth,
|
|
9
|
+
RequireScopes,
|
|
10
|
+
} from "@plasgos/auth-verify/nestjs";
|
|
11
|
+
import type { UserAccessPrincipal } from "@plasgos/auth-verify/nestjs";
|
|
12
|
+
import type { Response } from "express";
|
|
13
|
+
|
|
14
|
+
import { readTokenVerifierEnv } from "./env.js";
|
|
15
|
+
import { RevocationStoreUnavailableError, callerOf, logReject, revocationCheck } from "./token-verifier.js";
|
|
16
|
+
import type { RevocationStore } from "./token-verifier.js";
|
|
17
|
+
|
|
18
|
+
// #region module
|
|
19
|
+
/** Injection token of the app's marker store (for example a Redis client). */
|
|
20
|
+
export const REVOCATION_STORE = "REVOCATION_STORE";
|
|
21
|
+
|
|
22
|
+
@Module({})
|
|
23
|
+
export class RevocationStoreModule {
|
|
24
|
+
static register(store: RevocationStore): DynamicModule {
|
|
25
|
+
return {
|
|
26
|
+
module: RevocationStoreModule,
|
|
27
|
+
providers: [{ provide: REVOCATION_STORE, useValue: store }],
|
|
28
|
+
exports: [REVOCATION_STORE],
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The SDK's global module with options from a factory. The factory runs at bootstrap, so a wrong
|
|
35
|
+
* option stops the app with one ConfigError.
|
|
36
|
+
*/
|
|
37
|
+
export function plasgosAuthModule(store: RevocationStore): DynamicModule {
|
|
38
|
+
return PlasgosAuthModule.forRootAsync({
|
|
39
|
+
imports: [RevocationStoreModule.register(store)],
|
|
40
|
+
inject: [REVOCATION_STORE],
|
|
41
|
+
useFactory: (revocations: RevocationStore) => {
|
|
42
|
+
const env = readTokenVerifierEnv();
|
|
43
|
+
return {
|
|
44
|
+
environment: env.environment,
|
|
45
|
+
issuer: env.issuer,
|
|
46
|
+
audience: env.audience,
|
|
47
|
+
backchannelUrl: env.backchannelUrl,
|
|
48
|
+
allowInsecureBackchannel: env.allowInsecureBackchannel,
|
|
49
|
+
// Every route of the API: the user's public id and credential version are required.
|
|
50
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
51
|
+
isRevoked: revocationCheck(revocations),
|
|
52
|
+
onReject: logReject,
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
// #endregion module
|
|
58
|
+
|
|
59
|
+
// #region controller
|
|
60
|
+
@Controller("api/contacts")
|
|
61
|
+
@UseGuards(PlasgosAccessTokenGuard)
|
|
62
|
+
@RequireScopes("crm:access")
|
|
63
|
+
export class ContactsController {
|
|
64
|
+
@Get()
|
|
65
|
+
list(@PlasgosPrincipal() principal: UserAccessPrincipal): { owner: string; contacts: unknown[] } {
|
|
66
|
+
return { owner: callerOf(principal).publicId, contacts: [] };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** A sensitive action: the user signed in at most 10 minutes ago, else 401 with max_age=600. */
|
|
70
|
+
@Post("export")
|
|
71
|
+
@HttpCode(202)
|
|
72
|
+
@RequireRecentAuth(600)
|
|
73
|
+
exportContacts(@PlasgosPrincipal() principal: UserAccessPrincipal): { owner: string; queued: true } {
|
|
74
|
+
return { owner: callerOf(principal).publicId, queued: true };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// #endregion controller
|
|
78
|
+
|
|
79
|
+
// #region filter
|
|
80
|
+
/** The marker store is down inside isRevoked: 503, because the token itself may be fine. */
|
|
81
|
+
@Catch(RevocationStoreUnavailableError)
|
|
82
|
+
export class RevocationStoreUnavailableFilter implements ExceptionFilter {
|
|
83
|
+
catch(_error: RevocationStoreUnavailableError, host: ArgumentsHost): void {
|
|
84
|
+
const res = host.switchToHttp().getResponse<Response>();
|
|
85
|
+
res.setHeader("Retry-After", "5");
|
|
86
|
+
res.status(503).json({ error: "temporarily_unavailable" });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// #endregion filter
|
|
90
|
+
|
|
91
|
+
// #region app-module
|
|
92
|
+
/** NestFactory.create(AppModule.register(redis)): the store is the app's own client. */
|
|
93
|
+
@Module({})
|
|
94
|
+
export class AppModule {
|
|
95
|
+
static register(store: RevocationStore): DynamicModule {
|
|
96
|
+
return {
|
|
97
|
+
module: AppModule,
|
|
98
|
+
imports: [plasgosAuthModule(store)],
|
|
99
|
+
controllers: [ContactsController],
|
|
100
|
+
providers: [{ provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter }],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// #endregion app-module
|
|
105
|
+
|
|
106
|
+
// #region global-guard
|
|
107
|
+
/**
|
|
108
|
+
* Every route of the app behind the guard: register it once as APP_GUARD instead of @UseGuards on each
|
|
109
|
+
* controller. The SDK has no decorator that opens a route again, so serve health checks and other
|
|
110
|
+
* public routes from a separate app or port. Keep @RequireScopes on every controller: without a scope
|
|
111
|
+
* any valid token for your audience passes.
|
|
112
|
+
*/
|
|
113
|
+
@Module({})
|
|
114
|
+
export class GuardedAppModule {
|
|
115
|
+
static register(store: RevocationStore): DynamicModule {
|
|
116
|
+
return {
|
|
117
|
+
module: GuardedAppModule,
|
|
118
|
+
imports: [plasgosAuthModule(store)],
|
|
119
|
+
controllers: [ContactsController],
|
|
120
|
+
providers: [
|
|
121
|
+
{ provide: APP_GUARD, useClass: PlasgosAccessTokenGuard },
|
|
122
|
+
{ provide: APP_FILTER, useClass: RevocationStoreUnavailableFilter },
|
|
123
|
+
],
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// #endregion global-guard
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders } from "node:http";
|
|
2
|
+
|
|
3
|
+
import { AuthVerifyError } from "@plasgos/auth-verify";
|
|
4
|
+
import type { AccessTokenVerifier, UserAccessPrincipal } from "@plasgos/auth-verify";
|
|
5
|
+
|
|
6
|
+
// #region socket
|
|
7
|
+
/** The parts of a Socket.IO server socket this example uses. A socket.io 4 `Socket` fits it. */
|
|
8
|
+
export interface SocketLike {
|
|
9
|
+
readonly handshake: { readonly headers: IncomingHttpHeaders };
|
|
10
|
+
data: { principal?: UserAccessPrincipal };
|
|
11
|
+
disconnect(close?: boolean): unknown;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `io.use(socketAuth(verifier))`: checks the Authorization header of the handshake, which the BFF sets
|
|
16
|
+
* from the user's session, with the same verifier and scope as the HTTP routes. The error message
|
|
17
|
+
* reaches the browser as `connect_error`, so it names no reason and no value.
|
|
18
|
+
*/
|
|
19
|
+
export function socketAuth(verifier: AccessTokenVerifier) {
|
|
20
|
+
return (socket: SocketLike, next: (error?: Error) => void): void => {
|
|
21
|
+
verifier.verifyAuthorization(socket.handshake.headers.authorization, { scopes: ["crm:access"] }).then(
|
|
22
|
+
(principal) => {
|
|
23
|
+
socket.data.principal = principal;
|
|
24
|
+
next();
|
|
25
|
+
},
|
|
26
|
+
(error: unknown) => {
|
|
27
|
+
// A refused token: the browser renews its session (/auth/me at the BFF) and connects again.
|
|
28
|
+
// Anything else (the marker store is down): try again later.
|
|
29
|
+
next(new Error(error instanceof AuthVerifyError ? "unauthorized" : "unavailable"));
|
|
30
|
+
},
|
|
31
|
+
);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A socket outlives its token. Every few minutes each open socket's handshake token is verified again:
|
|
37
|
+
* expired, revoked or blocked closes the socket, and the browser connects again through the BFF with
|
|
38
|
+
* the session's current token. A store outage keeps the socket and checks it at the next round.
|
|
39
|
+
* With socket.io: `recheckSockets(verifier, () => io.of("/").sockets.values())`.
|
|
40
|
+
*/
|
|
41
|
+
export function recheckSockets(verifier: AccessTokenVerifier, sockets: () => Iterable<SocketLike>, everyMs = 5 * 60_000): () => void {
|
|
42
|
+
const timer = setInterval(() => {
|
|
43
|
+
for (const socket of sockets()) {
|
|
44
|
+
verifier.verifyAuthorization(socket.handshake.headers.authorization, { scopes: ["crm:access"] }).then(
|
|
45
|
+
(principal) => {
|
|
46
|
+
socket.data.principal = principal;
|
|
47
|
+
},
|
|
48
|
+
(error: unknown) => {
|
|
49
|
+
if (error instanceof AuthVerifyError) socket.disconnect(true);
|
|
50
|
+
},
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}, everyMs);
|
|
54
|
+
timer.unref();
|
|
55
|
+
return () => {
|
|
56
|
+
clearInterval(timer);
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
// #endregion socket
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { createAccessTokenVerifier } from "@plasgos/auth-verify";
|
|
4
|
+
import type { AccessTokenVerifier, JsonWebKeySet } from "@plasgos/auth-verify";
|
|
5
|
+
|
|
6
|
+
import { revocationCheck } from "./token-verifier.js";
|
|
7
|
+
import type { RevocationStore } from "./token-verifier.js";
|
|
8
|
+
|
|
9
|
+
// #region signer
|
|
10
|
+
/** A key pair made when the tests start, with node:crypto only. Never commit a key. */
|
|
11
|
+
export interface TestSigner {
|
|
12
|
+
/** The public key, for the sandbox-only `jwks` option of createAccessTokenVerifier. */
|
|
13
|
+
jwks: JsonWebKeySet;
|
|
14
|
+
/** An access token with these claims, signed the way Plasgos signs one (RS256, typ at+jwt). */
|
|
15
|
+
sign(claims: Record<string, unknown>): string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const base64url = (value: string | Buffer): string => Buffer.from(value).toString("base64url");
|
|
19
|
+
|
|
20
|
+
export function createTestSigner(): TestSigner {
|
|
21
|
+
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
22
|
+
const kid = `test-${randomUUID()}`;
|
|
23
|
+
const publicJwk = { ...publicKey.export({ format: "jwk" }), kid, alg: "RS256", use: "sig" };
|
|
24
|
+
return {
|
|
25
|
+
jwks: { keys: [publicJwk] },
|
|
26
|
+
sign(claims) {
|
|
27
|
+
const header = base64url(JSON.stringify({ alg: "RS256", typ: "at+jwt", kid }));
|
|
28
|
+
// JSON.stringify drops a claim whose value is undefined: testClaims({ cv: undefined }) has no cv.
|
|
29
|
+
const payload = base64url(JSON.stringify(claims));
|
|
30
|
+
const signature = sign("RSA-SHA256", Buffer.from(`${header}.${payload}`), privateKey);
|
|
31
|
+
return `${header}.${payload}.${base64url(signature)}`;
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// #endregion signer
|
|
36
|
+
|
|
37
|
+
// #region verifier
|
|
38
|
+
/** Test values: a sandbox issuer and a sandbox audience whose path is /crm, like the API's own. */
|
|
39
|
+
export const TEST_ISSUER = "https://accounts.sandbox.example";
|
|
40
|
+
export const TEST_AUDIENCE = "https://api.sandbox.example/crm";
|
|
41
|
+
|
|
42
|
+
/** The API's verifier for tests: the same rules as in production, the test key instead of the JWKS request. */
|
|
43
|
+
export function createTestVerifier(signer: TestSigner, store: RevocationStore): AccessTokenVerifier {
|
|
44
|
+
return createAccessTokenVerifier({
|
|
45
|
+
environment: "sandbox",
|
|
46
|
+
issuer: TEST_ISSUER,
|
|
47
|
+
audience: TEST_AUDIENCE,
|
|
48
|
+
// Sandbox only: a fixed key set, no request to Plasgos.
|
|
49
|
+
jwks: signer.jwks,
|
|
50
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
51
|
+
isRevoked: revocationCheck(store),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A marker store in memory, for tests. */
|
|
56
|
+
export function memoryRevocationStore(entries: Record<string, string> = {}): RevocationStore {
|
|
57
|
+
const markers = new Map(Object.entries(entries));
|
|
58
|
+
return { get: (key) => Promise.resolve(markers.get(key) ?? null) };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The claims of a user token as Plasgos issues them for this API. Override a claim, or drop it with undefined. */
|
|
62
|
+
export function testClaims(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
63
|
+
const now = Math.floor(Date.now() / 1000);
|
|
64
|
+
return {
|
|
65
|
+
iss: TEST_ISSUER,
|
|
66
|
+
aud: TEST_AUDIENCE,
|
|
67
|
+
sub: "pairwise-subject-1",
|
|
68
|
+
client_id: "test-client",
|
|
69
|
+
sid: "test-session-1",
|
|
70
|
+
auth_time: now - 60,
|
|
71
|
+
cv: 1,
|
|
72
|
+
plasgos_public_id: "usr-test-0001",
|
|
73
|
+
scope: "openid crm:access",
|
|
74
|
+
iat: now,
|
|
75
|
+
exp: now + 300,
|
|
76
|
+
...overrides,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
// #endregion verifier
|
|
80
|
+
|
|
81
|
+
// #region route-test
|
|
82
|
+
/** Your running API: 401 without a token, 200 with a good one, 403 without the scope, 401 when expired. */
|
|
83
|
+
export async function checkTokenRoute(url: string, signer: TestSigner): Promise<void> {
|
|
84
|
+
const call = (token: string | null): Promise<Response> =>
|
|
85
|
+
fetch(url, { headers: token === null ? {} : { Authorization: `Bearer ${token}` } });
|
|
86
|
+
const expectStatus = (res: Response, status: number, label: string): void => {
|
|
87
|
+
if (res.status !== status) throw new Error(`${label} answered ${String(res.status)}, expected ${String(status)}`);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const missing = await call(null);
|
|
91
|
+
expectStatus(missing, 401, "no token");
|
|
92
|
+
if (missing.headers.get("WWW-Authenticate") !== "Bearer") throw new Error("no token: WWW-Authenticate must be Bearer");
|
|
93
|
+
|
|
94
|
+
expectStatus(await call(signer.sign(testClaims())), 200, "good token");
|
|
95
|
+
expectStatus(await call(signer.sign(testClaims({ scope: "openid" }))), 403, "token without crm:access");
|
|
96
|
+
const past = Math.floor(Date.now() / 1000) - 600;
|
|
97
|
+
expectStatus(await call(signer.sign(testClaims({ iat: past, exp: past + 300 }))), 401, "expired token");
|
|
98
|
+
expectStatus(await call(signer.sign(testClaims({ cv: undefined }))), 401, "token without cv");
|
|
99
|
+
}
|
|
100
|
+
// #endregion route-test
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createAccessTokenVerifier } from "@plasgos/auth-verify";
|
|
2
|
+
import type { AccessPrincipal, AccessTokenVerifier, AuthRejectEvent, UserAccessPrincipal } from "@plasgos/auth-verify";
|
|
3
|
+
|
|
4
|
+
import { readTokenVerifierEnv } from "./env.js";
|
|
5
|
+
|
|
6
|
+
// #region revocation
|
|
7
|
+
/** The part of a key-value store the check reads. An ioredis or node-redis client fits it. */
|
|
8
|
+
export interface RevocationStore {
|
|
9
|
+
get(key: string): Promise<string | null>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Thrown when the marker store cannot be read. The app's error handler answers it with 503. */
|
|
13
|
+
export class RevocationStoreUnavailableError extends Error {
|
|
14
|
+
constructor(options?: ErrorOptions) {
|
|
15
|
+
super("revocation store unavailable", options);
|
|
16
|
+
this.name = "RevocationStoreUnavailableError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The app's own marker keys (the prefix is yours). Your webhook receiver writes them from the user.*
|
|
22
|
+
* events Plasgos sends to your app's webhook endpoint.
|
|
23
|
+
*/
|
|
24
|
+
export const revocationKeys = {
|
|
25
|
+
/** The newest credential version Plasgos announced for the user, as text ("3"). */
|
|
26
|
+
credentialVersion: (publicId: string): string => `myapp:revocation:cv:${publicId}`,
|
|
27
|
+
/** Present when the Plasgos session (`sid`) was revoked. */
|
|
28
|
+
session: (sessionId: string): string => `myapp:revocation:sid:${sessionId}`,
|
|
29
|
+
/** Present while the user is blocked. */
|
|
30
|
+
blockedUser: (publicId: string): string => `myapp:revocation:blocked:${publicId}`,
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The `isRevoked` hook: true refuses the token as `revoked` (401). Three checks:
|
|
35
|
+
* - the session was revoked (logout everywhere, a removed device);
|
|
36
|
+
* - the user is blocked;
|
|
37
|
+
* - the user's credentials changed after the token was issued (stored version above the token's `cv`).
|
|
38
|
+
*
|
|
39
|
+
* Without such a hook a token stays valid until it expires. When the store cannot be read the hook
|
|
40
|
+
* throws: the request fails with 503 instead of letting a revoked token through, and without a 401
|
|
41
|
+
* that would send every client to log in again because of an outage.
|
|
42
|
+
*/
|
|
43
|
+
export function revocationCheck(store: RevocationStore): (principal: UserAccessPrincipal) => Promise<boolean> {
|
|
44
|
+
return async (principal) => {
|
|
45
|
+
const publicId = principal.claims.plasgos_public_id;
|
|
46
|
+
const tokenVersion = principal.credentialVersion;
|
|
47
|
+
// requireClaims: ["plasgos_public_id", "cv"] already refuses such a token; the hook stays safe alone.
|
|
48
|
+
if (publicId === undefined || tokenVersion === null) return true;
|
|
49
|
+
|
|
50
|
+
let markers: (string | null)[];
|
|
51
|
+
try {
|
|
52
|
+
markers = await Promise.all([
|
|
53
|
+
store.get(revocationKeys.session(principal.sessionId)),
|
|
54
|
+
store.get(revocationKeys.blockedUser(publicId)),
|
|
55
|
+
store.get(revocationKeys.credentialVersion(publicId)),
|
|
56
|
+
]);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
// Never swallowed: an unreadable store must not count as "not revoked".
|
|
59
|
+
throw new RevocationStoreUnavailableError({ cause: error });
|
|
60
|
+
}
|
|
61
|
+
const [revokedSession, blocked, storedVersion] = markers;
|
|
62
|
+
if (revokedSession !== null || blocked !== null) return true;
|
|
63
|
+
if (storedVersion === null || storedVersion === undefined) return false;
|
|
64
|
+
const stored = Number(storedVersion);
|
|
65
|
+
// A marker this app did not write is a store problem, not a token problem.
|
|
66
|
+
if (!Number.isSafeInteger(stored)) throw new RevocationStoreUnavailableError();
|
|
67
|
+
return stored > tokenVersion;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
// #endregion revocation
|
|
71
|
+
|
|
72
|
+
// #region on-reject
|
|
73
|
+
/** One line per refused token. The event never holds the token or a claim value, so it is safe to log. */
|
|
74
|
+
export function logReject(event: AuthRejectEvent): void {
|
|
75
|
+
const line = [
|
|
76
|
+
"plasgos token refused:",
|
|
77
|
+
`env=${event.environment}`,
|
|
78
|
+
`reason=${event.reason}`,
|
|
79
|
+
`client_id=${event.clientId ?? "-"}`,
|
|
80
|
+
`request_id=${event.requestId ?? "-"}`,
|
|
81
|
+
].join(" ");
|
|
82
|
+
process.stderr.write(`${line}\n`);
|
|
83
|
+
// The key set of Plasgos cannot be read: every request answers 503 until it recovers.
|
|
84
|
+
if (event.reason === "unavailable") process.stderr.write("ALERT plasgos key set unavailable\n");
|
|
85
|
+
}
|
|
86
|
+
// #endregion on-reject
|
|
87
|
+
|
|
88
|
+
// #region create
|
|
89
|
+
/** Create it once at start: a wrong option throws one ConfigError there, before the first request. */
|
|
90
|
+
export function createApiTokenVerifier(store: RevocationStore): AccessTokenVerifier {
|
|
91
|
+
const env = readTokenVerifierEnv();
|
|
92
|
+
return createAccessTokenVerifier({
|
|
93
|
+
environment: env.environment,
|
|
94
|
+
issuer: env.issuer,
|
|
95
|
+
audience: env.audience,
|
|
96
|
+
backchannelUrl: env.backchannelUrl,
|
|
97
|
+
allowInsecureBackchannel: env.allowInsecureBackchannel,
|
|
98
|
+
// Every token must carry the user's public id and credential version.
|
|
99
|
+
requireClaims: ["plasgos_public_id", "cv"],
|
|
100
|
+
// Required for a crm audience: compares the session, the user and cv with the app's markers.
|
|
101
|
+
isRevoked: revocationCheck(store),
|
|
102
|
+
onReject: logReject,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
// #endregion create
|
|
106
|
+
|
|
107
|
+
// #region identity
|
|
108
|
+
/** The caller as this API knows it. */
|
|
109
|
+
export interface Caller {
|
|
110
|
+
/** The user's public id (`usr-…`): the same in every app, so it is the user key of this API. */
|
|
111
|
+
publicId: string;
|
|
112
|
+
/** The Plasgos session (`sid`). */
|
|
113
|
+
sessionId: string;
|
|
114
|
+
/** The credential version (`cv`) the token was issued with. */
|
|
115
|
+
credentialVersion: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The caller of a verified token. `principal.subject` is pairwise (a different value for every client
|
|
120
|
+
* that calls this API), so the user is identified by `claims.plasgos_public_id`, never by `subject`.
|
|
121
|
+
*/
|
|
122
|
+
export function callerOf(principal: AccessPrincipal): Caller {
|
|
123
|
+
if (principal.kind !== "user") throw new Error("this API accepts user tokens only");
|
|
124
|
+
const publicId = principal.claims.plasgos_public_id;
|
|
125
|
+
const credentialVersion = principal.credentialVersion;
|
|
126
|
+
// requireClaims: ["plasgos_public_id", "cv"] guarantees both; the check narrows the types.
|
|
127
|
+
if (publicId === undefined || credentialVersion === null) {
|
|
128
|
+
throw new Error("the verifier must require plasgos_public_id and cv");
|
|
129
|
+
}
|
|
130
|
+
return { publicId, sessionId: principal.sessionId, credentialVersion };
|
|
131
|
+
}
|
|
132
|
+
// #endregion identity
|