@plasgos/oidc-client 0.1.0-next.2 → 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 +17 -0
- package/README.md +7 -3
- package/dist/session.cjs +71 -20
- package/dist/session.cjs.map +1 -1
- package/dist/session.d.cts +55 -4
- package/dist/session.d.ts +55 -4
- package/dist/session.js +63 -13
- package/dist/session.js.map +1 -1
- package/docs/bff-express.md +1314 -0
- package/docs/consumers.md +10 -2
- package/docs/error.md +195 -10
- package/docs/examples/auth-verify-readme.ts +24 -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/env.ts +52 -1
- 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-verifier.ts +54 -0
- package/docs/login-web.md +39 -7
- package/docs/memulai.md +94 -14
- package/docs/server-ke-server.md +12 -0
- package/docs/verifikasi-token.md +1219 -0
- package/docs/webhook.md +191 -6
- package/package.json +2 -2
package/docs/examples/env.ts
CHANGED
|
@@ -86,7 +86,8 @@ export function readSessionSecrets(): string[] {
|
|
|
86
86
|
// #region webhook-secrets
|
|
87
87
|
/**
|
|
88
88
|
* A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
|
|
89
|
-
* PLASGOS_WEBHOOK_SECRET (payments
|
|
89
|
+
* PLASGOS_WEBHOOK_SECRET (the app webhook endpoint: payments and every other app event, one secret)
|
|
90
|
+
* and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
|
|
90
91
|
*/
|
|
91
92
|
export function readWebhookSecrets(name: string): string[] {
|
|
92
93
|
const secrets = required(name)
|
|
@@ -97,3 +98,53 @@ export function readWebhookSecrets(name: string): string[] {
|
|
|
97
98
|
return secrets;
|
|
98
99
|
}
|
|
99
100
|
// #endregion webhook-secrets
|
|
101
|
+
|
|
102
|
+
// #region token-verifier
|
|
103
|
+
/** What an API that verifies Plasgos access tokens reads. */
|
|
104
|
+
export interface TokenVerifierEnv {
|
|
105
|
+
environment: Environment;
|
|
106
|
+
/** PLASGOS_ISSUER: the token's `iss` must equal it. */
|
|
107
|
+
issuer: string;
|
|
108
|
+
/** PLASGOS_TOKEN_AUDIENCE: the audience of this API, given by the Plasgos team; the token's `aud` must equal it. */
|
|
109
|
+
audience: string;
|
|
110
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin for the key set (JWKS), only inside the Plasgos network. */
|
|
111
|
+
backchannelUrl: string | undefined;
|
|
112
|
+
/** PLASGOS_ALLOW_INSECURE_BACKCHANNEL=true: production only, an http: back channel on a private network you trust. */
|
|
113
|
+
allowInsecureBackchannel: boolean;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function readTokenVerifierEnv(): TokenVerifierEnv {
|
|
117
|
+
return {
|
|
118
|
+
environment: readEnvironment(),
|
|
119
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
120
|
+
audience: required("PLASGOS_TOKEN_AUDIENCE"),
|
|
121
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
122
|
+
allowInsecureBackchannel: optional("PLASGOS_ALLOW_INSECURE_BACKCHANNEL") === "true",
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
// #endregion token-verifier
|
|
126
|
+
|
|
127
|
+
// #region bff
|
|
128
|
+
/** What a backend-for-frontend (BFF) reads besides its login credentials and its session secret. */
|
|
129
|
+
export interface BffEnv {
|
|
130
|
+
environment: Environment;
|
|
131
|
+
/** PLASGOS_ISSUER: where users log in and tokens are issued. */
|
|
132
|
+
issuer: string;
|
|
133
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
|
|
134
|
+
backchannelUrl: string | undefined;
|
|
135
|
+
/** PLASGOS_RESOURCE: the audience of the app's own API; every token is requested for it. */
|
|
136
|
+
resource: string;
|
|
137
|
+
/** APP_API_URL: origin of the app's own API behind the BFF (not a Plasgos value). */
|
|
138
|
+
apiOrigin: string;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function readBffEnv(): BffEnv {
|
|
142
|
+
return {
|
|
143
|
+
environment: readEnvironment(),
|
|
144
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
145
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
146
|
+
resource: required("PLASGOS_RESOURCE"),
|
|
147
|
+
apiOrigin: required("APP_API_URL").replace(/\/$/, ""),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
// #endregion bff
|
|
@@ -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
|