@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,150 @@
|
|
|
1
|
+
/** Same values as the SDK's `Environment` type. */
|
|
2
|
+
type Environment = "sandbox" | "production";
|
|
3
|
+
|
|
4
|
+
function required(name: string): string {
|
|
5
|
+
const value = process.env[name]?.trim() ?? "";
|
|
6
|
+
if (value === "") throw new Error(`Environment variable ${name} is required`);
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function optional(name: string): string | undefined {
|
|
11
|
+
const value = process.env[name]?.trim() ?? "";
|
|
12
|
+
return value === "" ? undefined : value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** PLASGOS_ENV: "sandbox" or "production". There is no default on purpose. */
|
|
16
|
+
export function readEnvironment(): Environment {
|
|
17
|
+
const value = required("PLASGOS_ENV");
|
|
18
|
+
if (value !== "sandbox" && value !== "production") {
|
|
19
|
+
throw new Error('Environment variable PLASGOS_ENV must be "sandbox" or "production"');
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** What every Plasgos client of this app shares. */
|
|
25
|
+
export interface PlasgosEnv {
|
|
26
|
+
environment: Environment;
|
|
27
|
+
/** PLASGOS_ISSUER: where users log in and tokens are issued. */
|
|
28
|
+
issuer: string;
|
|
29
|
+
/** PLASGOS_API_URL: where /v5/* lives. */
|
|
30
|
+
apiUrl: string;
|
|
31
|
+
/** PLASGOS_BACKCHANNEL_URL: optional internal origin of the Plasgos server, only inside the Plasgos network. */
|
|
32
|
+
backchannelUrl: string | undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function readPlasgosEnv(): PlasgosEnv {
|
|
36
|
+
return {
|
|
37
|
+
environment: readEnvironment(),
|
|
38
|
+
issuer: required("PLASGOS_ISSUER"),
|
|
39
|
+
apiUrl: required("PLASGOS_API_URL"),
|
|
40
|
+
backchannelUrl: optional("PLASGOS_BACKCHANNEL_URL"),
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Credentials of the service client (server-to-server). */
|
|
45
|
+
export interface ServiceCredentials {
|
|
46
|
+
clientId: string;
|
|
47
|
+
clientSecret: string;
|
|
48
|
+
/** PLASGOS_AUDIENCE: only when the environment does not use the default platform audience. */
|
|
49
|
+
audience: string | undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function readServiceCredentials(): ServiceCredentials {
|
|
53
|
+
return {
|
|
54
|
+
clientId: required("PLASGOS_SERVICE_CLIENT_ID"),
|
|
55
|
+
clientSecret: required("PLASGOS_SERVICE_CLIENT_SECRET"),
|
|
56
|
+
audience: optional("PLASGOS_AUDIENCE"),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Credentials of the login client (interactive), and the public origin of this app. */
|
|
61
|
+
export interface LoginCredentials {
|
|
62
|
+
clientId: string;
|
|
63
|
+
clientSecret: string;
|
|
64
|
+
/** APP_URL: public origin of this app, for example https://app.example.com. */
|
|
65
|
+
appUrl: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function readLoginCredentials(): LoginCredentials {
|
|
69
|
+
return {
|
|
70
|
+
clientId: required("PLASGOS_LOGIN_CLIENT_ID"),
|
|
71
|
+
clientSecret: required("PLASGOS_LOGIN_CLIENT_SECRET"),
|
|
72
|
+
appUrl: required("APP_URL").replace(/\/$/, ""),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** SESSION_SECRET: one secret, or "new,old" while a rotation is in progress. */
|
|
77
|
+
export function readSessionSecrets(): string[] {
|
|
78
|
+
const secrets = required("SESSION_SECRET")
|
|
79
|
+
.split(",")
|
|
80
|
+
.map((secret) => secret.trim())
|
|
81
|
+
.filter((secret) => secret !== "");
|
|
82
|
+
if (secrets.length > 2) throw new Error("Environment variable SESSION_SECRET holds at most two secrets");
|
|
83
|
+
return secrets;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// #region webhook-secrets
|
|
87
|
+
/**
|
|
88
|
+
* A webhook secret: one secret, or "new,old" while a rotation is in progress. Names used in the guides:
|
|
89
|
+
* PLASGOS_WEBHOOK_SECRET (the app webhook endpoint: payments and every other app event, one secret)
|
|
90
|
+
* and PLASGOS_SHIPPING_WEBHOOK_SECRET (Plaslink shipping).
|
|
91
|
+
*/
|
|
92
|
+
export function readWebhookSecrets(name: string): string[] {
|
|
93
|
+
const secrets = required(name)
|
|
94
|
+
.split(",")
|
|
95
|
+
.map((secret) => secret.trim())
|
|
96
|
+
.filter((secret) => secret !== "");
|
|
97
|
+
if (secrets.length > 2) throw new Error(`Environment variable ${name} holds at most two secrets`);
|
|
98
|
+
return secrets;
|
|
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,18 @@
|
|
|
1
|
+
import type { OidcFailureEvent } from "@plasgos/oidc-client";
|
|
2
|
+
|
|
3
|
+
/** One line per failure. The event never holds a token, a secret or a response body, so it is safe to log. */
|
|
4
|
+
export function logFailure(event: OidcFailureEvent): void {
|
|
5
|
+
const line = [
|
|
6
|
+
"plasgos auth failed:",
|
|
7
|
+
`env=${event.environment}`,
|
|
8
|
+
`operation=${event.operation}`,
|
|
9
|
+
`reason=${event.reason}`,
|
|
10
|
+
`call=${event.method ?? "-"} ${event.path ?? "-"}`,
|
|
11
|
+
`status=${event.status === null ? "-" : String(event.status)}`,
|
|
12
|
+
`request_id=${event.requestId ?? "-"}`,
|
|
13
|
+
`provider_error=${event.providerError ?? "-"}`,
|
|
14
|
+
].join(" ");
|
|
15
|
+
process.stderr.write(`${line}\n`);
|
|
16
|
+
// A wrong secret, scope or grant is a bug in this app's configuration: page someone.
|
|
17
|
+
if (event.reason === "config_invalid") process.stderr.write("ALERT plasgos client configuration refused\n");
|
|
18
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createOidcClient } from "@plasgos/oidc-client";
|
|
2
|
+
import type { OidcClient } from "@plasgos/oidc-client";
|
|
3
|
+
|
|
4
|
+
import { readLoginCredentials, readPlasgosEnv } from "./env.js";
|
|
5
|
+
import { logFailure } from "./failure-log.js";
|
|
6
|
+
|
|
7
|
+
// #region first-party
|
|
8
|
+
/** A Plasgos app (BFF): tokens for one Plasgos API, refresh token, logout without a confirmation page. */
|
|
9
|
+
export function createFirstPartyClient(): OidcClient {
|
|
10
|
+
const env = readPlasgosEnv();
|
|
11
|
+
const credentials = readLoginCredentials();
|
|
12
|
+
return createOidcClient({
|
|
13
|
+
environment: env.environment,
|
|
14
|
+
issuer: env.issuer,
|
|
15
|
+
backchannelUrl: env.backchannelUrl,
|
|
16
|
+
clientId: credentials.clientId,
|
|
17
|
+
clientSecret: credentials.clientSecret,
|
|
18
|
+
redirectUri: `${credentials.appUrl}/auth/callback`,
|
|
19
|
+
postLogoutRedirectUri: `${credentials.appUrl}/`,
|
|
20
|
+
scopes: ["openid", "profile", "email", "packages:read", "packages:write"],
|
|
21
|
+
profile: "first-party",
|
|
22
|
+
// The audience of the API this app calls. Required by the packages:* scopes.
|
|
23
|
+
resource: process.env.PLASGOS_RESOURCE,
|
|
24
|
+
onFailure: logFailure,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
// #endregion first-party
|
|
28
|
+
|
|
29
|
+
// #region third-party
|
|
30
|
+
/** An app outside Plasgos: identity only. No resource, no logout ticket. */
|
|
31
|
+
export function createThirdPartyClient(): OidcClient {
|
|
32
|
+
const env = readPlasgosEnv();
|
|
33
|
+
const credentials = readLoginCredentials();
|
|
34
|
+
return createOidcClient({
|
|
35
|
+
environment: env.environment,
|
|
36
|
+
issuer: env.issuer,
|
|
37
|
+
clientId: credentials.clientId,
|
|
38
|
+
clientSecret: credentials.clientSecret,
|
|
39
|
+
redirectUri: `${credentials.appUrl}/auth/callback`,
|
|
40
|
+
postLogoutRedirectUri: `${credentials.appUrl}/`,
|
|
41
|
+
scopes: ["openid", "profile", "email", "plaslink:shipping"],
|
|
42
|
+
profile: "third-party",
|
|
43
|
+
onFailure: logFailure,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// #endregion third-party
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { OidcError, accessTokenExpiry } from "@plasgos/oidc-client";
|
|
2
|
+
import type { OidcClient } from "@plasgos/oidc-client";
|
|
3
|
+
import type { AuthState, SessionHandle, SessionStore } from "@plasgos/oidc-client/session";
|
|
4
|
+
|
|
5
|
+
import { readLoginCredentials, readPlasgosEnv } from "./env.js";
|
|
6
|
+
import { createFirstPartyClient } from "./login-client.js";
|
|
7
|
+
import { createAppSessionStore } from "./session-store.js";
|
|
8
|
+
import type { AppSession } from "./session-store.js";
|
|
9
|
+
|
|
10
|
+
// #region setup
|
|
11
|
+
/** Everything the handlers need. Create it once at start and pass it to every handler. */
|
|
12
|
+
export interface AuthContext {
|
|
13
|
+
client: OidcClient;
|
|
14
|
+
store: SessionStore<AppSession>;
|
|
15
|
+
/** Public origin of this app, for the Origin check of the logout. */
|
|
16
|
+
appOrigin: string;
|
|
17
|
+
/** Where /v5/* lives. */
|
|
18
|
+
apiUrl: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createAuthContext(): AuthContext {
|
|
22
|
+
return {
|
|
23
|
+
client: createFirstPartyClient(),
|
|
24
|
+
store: createAppSessionStore(),
|
|
25
|
+
appOrigin: readLoginCredentials().appUrl,
|
|
26
|
+
apiUrl: readPlasgosEnv().apiUrl,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Only a path of this app is accepted as the place to return to after login. */
|
|
31
|
+
function safeReturnTo(value: string | null): string {
|
|
32
|
+
if (value === null || value.length > 512) return "/";
|
|
33
|
+
if (!value.startsWith("/") || value.startsWith("//") || value.startsWith("/\\")) return "/";
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function redirect(location: string, headers: Headers, status = 302): Response {
|
|
38
|
+
headers.set("Location", location);
|
|
39
|
+
headers.set("Cache-Control", "no-store");
|
|
40
|
+
return new Response(null, { status, headers });
|
|
41
|
+
}
|
|
42
|
+
// #endregion setup
|
|
43
|
+
|
|
44
|
+
// #region login
|
|
45
|
+
/** GET /login?returnTo=/path: a full-page redirect to Plasgos. */
|
|
46
|
+
export function handleLogin(context: AuthContext, request: Request): Response {
|
|
47
|
+
const returnTo = safeReturnTo(new URL(request.url).searchParams.get("returnTo"));
|
|
48
|
+
const { location, transaction } = context.client.startLogin({ returnTo });
|
|
49
|
+
const headers = new Headers();
|
|
50
|
+
headers.append("Set-Cookie", context.store.commitTransaction(transaction));
|
|
51
|
+
return redirect(location, headers);
|
|
52
|
+
}
|
|
53
|
+
// #endregion login
|
|
54
|
+
|
|
55
|
+
// #region callback
|
|
56
|
+
function loginFailed(headers: Headers, status: number): Response {
|
|
57
|
+
headers.set("Cache-Control", "no-store");
|
|
58
|
+
headers.set("Content-Type", "text/plain; charset=utf-8");
|
|
59
|
+
return new Response("Login gagal. Silakan coba lagi.", { status, headers });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** GET /auth/callback: Plasgos sends the browser back here with `code` and `state`. */
|
|
63
|
+
export async function handleCallback(context: AuthContext, request: Request): Promise<Response> {
|
|
64
|
+
const { client, store } = context;
|
|
65
|
+
const headers = new Headers();
|
|
66
|
+
// The transaction is single use: its cookie is cleared whatever happens next.
|
|
67
|
+
headers.append("Set-Cookie", store.clearTransaction());
|
|
68
|
+
try {
|
|
69
|
+
const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
|
|
70
|
+
const auth: AuthState = {
|
|
71
|
+
access_token: tokens.access_token,
|
|
72
|
+
refresh_token: tokens.refresh_token,
|
|
73
|
+
expires_at: accessTokenExpiry(tokens, Date.now()),
|
|
74
|
+
user: {
|
|
75
|
+
id: claims.sub,
|
|
76
|
+
name: claims.name ?? "",
|
|
77
|
+
email: claims.email ?? null,
|
|
78
|
+
avatar_url: claims.picture ?? null,
|
|
79
|
+
},
|
|
80
|
+
id_token: tokens.id_token,
|
|
81
|
+
auth_time: claims.auth_time,
|
|
82
|
+
};
|
|
83
|
+
const fits = store.fits(auth);
|
|
84
|
+
if (!fits.auth) return loginFailed(headers, 500);
|
|
85
|
+
const session = store.read(request);
|
|
86
|
+
// Without the ID token the session still works; only the logout then asks the user to confirm.
|
|
87
|
+
session.update({ auth: fits.idToken ? auth : { ...auth, id_token: undefined } });
|
|
88
|
+
for (const cookie of store.commit(session)) headers.append("Set-Cookie", cookie);
|
|
89
|
+
return redirect(safeReturnTo(transaction.return_to), headers);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (!(error instanceof OidcError)) throw error;
|
|
92
|
+
return loginFailed(headers, error.reason === "unavailable" ? 503 : 400);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// #endregion callback
|
|
96
|
+
|
|
97
|
+
// #region logout
|
|
98
|
+
/** POST /logout, from a form of this app. */
|
|
99
|
+
export async function handleLogout(context: AuthContext, request: Request): Promise<Response> {
|
|
100
|
+
const { client, store } = context;
|
|
101
|
+
if (request.method !== "POST") return new Response(null, { status: 405, headers: { Allow: "POST" } });
|
|
102
|
+
// Another site must not be able to log the user out.
|
|
103
|
+
if (request.headers.get("Origin") !== context.appOrigin) return new Response(null, { status: 403 });
|
|
104
|
+
|
|
105
|
+
const session = store.read(request);
|
|
106
|
+
const auth = session.data.auth;
|
|
107
|
+
// Never rejects: a failed call to Plasgos is reported through onFailure and the logout goes on.
|
|
108
|
+
const result = await client.logout({
|
|
109
|
+
refreshToken: auth?.refresh_token,
|
|
110
|
+
idToken: auth?.id_token,
|
|
111
|
+
// clientIp: the address your reverse proxy vouches for, or null.
|
|
112
|
+
browser: { clientIp: null, userAgent: request.headers.get("User-Agent") },
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
session.destroy();
|
|
116
|
+
const headers = new Headers();
|
|
117
|
+
for (const cookie of store.commit(session)) headers.append("Set-Cookie", cookie);
|
|
118
|
+
if (result.kind !== "redirect") throw new Error('This app uses endSession "redirect"');
|
|
119
|
+
return redirect(result.location, headers, 303);
|
|
120
|
+
}
|
|
121
|
+
// #endregion logout
|
|
122
|
+
|
|
123
|
+
// #region fresh
|
|
124
|
+
/** The access token to use now, renewed when it is about to expire; null when nobody is signed in. */
|
|
125
|
+
async function freshAccessToken(
|
|
126
|
+
context: AuthContext,
|
|
127
|
+
session: SessionHandle<AppSession>,
|
|
128
|
+
force = false,
|
|
129
|
+
): Promise<string | null> {
|
|
130
|
+
const current = session.data.auth;
|
|
131
|
+
if (current === undefined) return null;
|
|
132
|
+
const { auth, changed } = await context.client.ensureFresh(current, { force });
|
|
133
|
+
// Store a renewed auth at once: its refresh token replaced the old one at Plasgos.
|
|
134
|
+
if (changed) session.update({ auth });
|
|
135
|
+
return auth.access_token;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const isInvalidToken = (res: Response): boolean =>
|
|
139
|
+
res.status === 401 && (res.headers.get("WWW-Authenticate") ?? "").includes("invalid_token");
|
|
140
|
+
|
|
141
|
+
/** Calls a Plasgos API for the signed-in user and answers with its body. */
|
|
142
|
+
export async function callApi(context: AuthContext, request: Request, path: string): Promise<Response> {
|
|
143
|
+
const session = context.store.read(request);
|
|
144
|
+
/** Every answer carries the session cookies that changed, also an error answer. */
|
|
145
|
+
const respond = (body: ReadableStream<Uint8Array> | string | null, status: number, headers = new Headers()): Response => {
|
|
146
|
+
for (const cookie of context.store.commit(session)) headers.append("Set-Cookie", cookie);
|
|
147
|
+
headers.set("Cache-Control", "no-store");
|
|
148
|
+
return new Response(body, { status, headers });
|
|
149
|
+
};
|
|
150
|
+
const toLogin = (): Response => {
|
|
151
|
+
const { pathname, search } = new URL(request.url);
|
|
152
|
+
return respond(null, 302, new Headers({ Location: `/login?returnTo=${encodeURIComponent(pathname + search)}` }));
|
|
153
|
+
};
|
|
154
|
+
const call = (token: string): Promise<Response> =>
|
|
155
|
+
fetch(`${context.apiUrl}${path}`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json" } });
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
let token = await freshAccessToken(context, session);
|
|
159
|
+
if (token === null) return toLogin();
|
|
160
|
+
let res = await call(token);
|
|
161
|
+
if (isInvalidToken(res)) {
|
|
162
|
+
// The API refused a token that looked valid: refresh once and try once more.
|
|
163
|
+
token = await freshAccessToken(context, session, true);
|
|
164
|
+
if (token === null) return toLogin();
|
|
165
|
+
res = await call(token);
|
|
166
|
+
}
|
|
167
|
+
return respond(res.body, res.status, new Headers({ "Content-Type": res.headers.get("Content-Type") ?? "application/json" }));
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (!(error instanceof OidcError)) throw error;
|
|
170
|
+
switch (error.reason) {
|
|
171
|
+
// The session is over at Plasgos: clear it here and send the user to login.
|
|
172
|
+
case "invalid_grant":
|
|
173
|
+
case "invalid_target":
|
|
174
|
+
case "missing":
|
|
175
|
+
session.update({ auth: undefined });
|
|
176
|
+
return toLogin();
|
|
177
|
+
// Plasgos did not answer and the access token has run out. The session is kept.
|
|
178
|
+
case "unavailable":
|
|
179
|
+
return respond("Layanan sedang tidak tersedia. Coba lagi sebentar.", 503);
|
|
180
|
+
// config_invalid and anything else: a bug to fix. The session is kept.
|
|
181
|
+
default:
|
|
182
|
+
return respond("Terjadi kesalahan.", 500);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
// #endregion fresh
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { OidcError } from "@plasgos/oidc-client";
|
|
2
|
+
import type { OidcClient } from "@plasgos/oidc-client";
|
|
3
|
+
import type { SessionStore } from "@plasgos/oidc-client/session";
|
|
4
|
+
|
|
5
|
+
import type { AppSession } from "./session-store.js";
|
|
6
|
+
|
|
7
|
+
// #region start
|
|
8
|
+
/** GET /plasgos/connect: sends the seller to Plasgos to approve the connection. */
|
|
9
|
+
export function startConnect(client: OidcClient, store: SessionStore<AppSession>): Response {
|
|
10
|
+
const { location, transaction } = client.startLogin({ returnTo: "/settings/plasgos" });
|
|
11
|
+
return new Response(null, {
|
|
12
|
+
status: 302,
|
|
13
|
+
headers: {
|
|
14
|
+
Location: location,
|
|
15
|
+
"Set-Cookie": store.commitTransaction(transaction),
|
|
16
|
+
"Cache-Control": "no-store",
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
// #endregion start
|
|
21
|
+
|
|
22
|
+
// #region callback
|
|
23
|
+
/** The Plasgos account a seller connected. `subject` is stable for this client and differs per client. */
|
|
24
|
+
export interface ConnectedSeller {
|
|
25
|
+
subject: string;
|
|
26
|
+
name: string | null;
|
|
27
|
+
email: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* GET /auth/callback: returns the connected seller, or null when the connection failed.
|
|
32
|
+
* Append `setCookie` to the response either way: it clears the single-use transaction cookie.
|
|
33
|
+
*/
|
|
34
|
+
export async function finishConnect(
|
|
35
|
+
client: OidcClient,
|
|
36
|
+
store: SessionStore<AppSession>,
|
|
37
|
+
request: Request,
|
|
38
|
+
): Promise<{ seller: ConnectedSeller | null; setCookie: string }> {
|
|
39
|
+
const setCookie = store.clearTransaction();
|
|
40
|
+
try {
|
|
41
|
+
const { claims } = await client.handleCallback(request.url, store.readTransaction(request));
|
|
42
|
+
return { seller: { subject: claims.sub, name: claims.name ?? null, email: claims.email ?? null }, setCookie };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (!(error instanceof OidcError)) throw error;
|
|
45
|
+
return { seller: null, setCookie };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
// #endregion callback
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { createOidcClient } from "@plasgos/oidc-client";
|
|
2
|
+
import type { OidcClient } from "@plasgos/oidc-client";
|
|
3
|
+
import { createServiceClient } from "@plasgos/oidc-client/service";
|
|
4
|
+
import { createSessionStore } from "@plasgos/oidc-client/session";
|
|
5
|
+
import type { SessionStore, SessionUser } from "@plasgos/oidc-client/session";
|
|
6
|
+
|
|
7
|
+
// #region login
|
|
8
|
+
export function createClient(): OidcClient {
|
|
9
|
+
return createOidcClient({
|
|
10
|
+
environment: "production",
|
|
11
|
+
issuer: "https://accounts.plasgos.co.id",
|
|
12
|
+
clientId: process.env.PLASGOS_LOGIN_CLIENT_ID ?? "",
|
|
13
|
+
clientSecret: process.env.PLASGOS_LOGIN_CLIENT_SECRET ?? "",
|
|
14
|
+
redirectUri: "https://app.example.com/auth/callback",
|
|
15
|
+
scopes: ["openid", "profile", "email"],
|
|
16
|
+
profile: "third-party",
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** GET /login: redirects the browser to Plasgos. */
|
|
21
|
+
export function login(client: OidcClient, store: SessionStore<object>): Response {
|
|
22
|
+
const { location, transaction } = client.startLogin({ returnTo: "/" });
|
|
23
|
+
const headers = { Location: location, "Set-Cookie": store.commitTransaction(transaction) };
|
|
24
|
+
return new Response(null, { status: 302, headers });
|
|
25
|
+
}
|
|
26
|
+
// #endregion login
|
|
27
|
+
|
|
28
|
+
// #region session
|
|
29
|
+
export function createStore(): SessionStore<object> {
|
|
30
|
+
return createSessionStore<object>({
|
|
31
|
+
environment: "production",
|
|
32
|
+
secrets: [process.env.SESSION_SECRET ?? ""],
|
|
33
|
+
hkdfSalt: "app-example",
|
|
34
|
+
cookies: { app: "ax", auth: "ax-auth", idToken: "ax-idt", transaction: "ax-oidc" },
|
|
35
|
+
authMaxAgeSeconds: 2_592_000,
|
|
36
|
+
// This app keeps no data of its own in the session, only the SDK's auth.
|
|
37
|
+
appSchema: { parse: () => ({}) },
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The signed-in user of a request, or null. */
|
|
42
|
+
export function currentUser(store: SessionStore<object>, request: Request): SessionUser | null {
|
|
43
|
+
return store.read(request).data.auth?.user ?? null;
|
|
44
|
+
}
|
|
45
|
+
// #endregion session
|
|
46
|
+
|
|
47
|
+
// #region service
|
|
48
|
+
export async function whoAmI(): Promise<unknown> {
|
|
49
|
+
const plasgos = createServiceClient({
|
|
50
|
+
environment: "production",
|
|
51
|
+
issuer: "https://accounts.plasgos.co.id",
|
|
52
|
+
apiUrl: "https://api.plasgos.co.id",
|
|
53
|
+
clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
|
|
54
|
+
clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
|
|
55
|
+
scopes: ["platform:self.read"],
|
|
56
|
+
});
|
|
57
|
+
const res = await plasgos.fetch("/v5/service/me");
|
|
58
|
+
return res.json();
|
|
59
|
+
}
|
|
60
|
+
// #endregion service
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { OidcError, createServiceClient } from "@plasgos/oidc-client/service";
|
|
2
|
+
import type { ServiceClient } from "@plasgos/oidc-client/service";
|
|
3
|
+
|
|
4
|
+
import { readPlasgosEnv, readServiceCredentials } from "./env.js";
|
|
5
|
+
import { logFailure } from "./failure-log.js";
|
|
6
|
+
|
|
7
|
+
// #region create
|
|
8
|
+
/** Create it once at start and reuse it: the token cache lives in the client. */
|
|
9
|
+
export function createPlasgosClient(): ServiceClient {
|
|
10
|
+
const env = readPlasgosEnv();
|
|
11
|
+
const credentials = readServiceCredentials();
|
|
12
|
+
return createServiceClient({
|
|
13
|
+
environment: env.environment,
|
|
14
|
+
issuer: env.issuer,
|
|
15
|
+
apiUrl: env.apiUrl,
|
|
16
|
+
backchannelUrl: env.backchannelUrl,
|
|
17
|
+
clientId: credentials.clientId,
|
|
18
|
+
clientSecret: credentials.clientSecret,
|
|
19
|
+
scopes: ["platform:self.read", "payments:read", "payments:write"],
|
|
20
|
+
resource: credentials.audience,
|
|
21
|
+
onFailure: logFailure,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
// #endregion create
|
|
25
|
+
|
|
26
|
+
// #region self-check
|
|
27
|
+
/** GET /v5/service/me: proves the credentials, the scope and the network path. Needs platform:self.read. */
|
|
28
|
+
export async function checkConnection(plasgos: ServiceClient): Promise<unknown> {
|
|
29
|
+
const res = await plasgos.fetch("/v5/service/me");
|
|
30
|
+
if (!res.ok) throw new Error(`Plasgos self check answered ${String(res.status)}`);
|
|
31
|
+
return res.json();
|
|
32
|
+
}
|
|
33
|
+
// #endregion self-check
|
|
34
|
+
|
|
35
|
+
// #region create-payment
|
|
36
|
+
export interface NewPayment {
|
|
37
|
+
/** Your own id of the bill. Sending the same body again returns the same payment (200, not 201). */
|
|
38
|
+
external_ref: string;
|
|
39
|
+
/** A payment purpose registered for your app, for example "subscription". */
|
|
40
|
+
purpose: string;
|
|
41
|
+
amount: { amount: number; currency: "IDR" };
|
|
42
|
+
customer: { name: string; email: string };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** POST /v5/service/payments. Needs payments:write. */
|
|
46
|
+
export async function createPayment(plasgos: ServiceClient, payment: NewPayment): Promise<unknown> {
|
|
47
|
+
const res = await plasgos.fetch("/v5/service/payments", {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: { "Content-Type": "application/json" },
|
|
50
|
+
body: JSON.stringify(payment),
|
|
51
|
+
});
|
|
52
|
+
if (!res.ok) throw new Error(`Plasgos payments answered ${String(res.status)}`);
|
|
53
|
+
return res.json();
|
|
54
|
+
}
|
|
55
|
+
// #endregion create-payment
|
|
56
|
+
|
|
57
|
+
// #region first-payment
|
|
58
|
+
/** A subscription bill of this app, paid through Plasgos. */
|
|
59
|
+
export function createSubscriptionPayment(
|
|
60
|
+
plasgos: ServiceClient,
|
|
61
|
+
bill: { id: string; amountRupiah: number; sellerName: string; sellerEmail: string },
|
|
62
|
+
): Promise<unknown> {
|
|
63
|
+
return createPayment(plasgos, {
|
|
64
|
+
external_ref: bill.id,
|
|
65
|
+
purpose: "subscription",
|
|
66
|
+
amount: { amount: bill.amountRupiah, currency: "IDR" },
|
|
67
|
+
customer: { name: bill.sellerName, email: bill.sellerEmail },
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
// #endregion first-payment
|
|
71
|
+
|
|
72
|
+
// #region refund
|
|
73
|
+
/** POST /v5/service/payments/{pay_id}/refunds. Needs payments:refund and an Idempotency-Key. */
|
|
74
|
+
export async function refundPayment(
|
|
75
|
+
plasgos: ServiceClient,
|
|
76
|
+
paymentId: string,
|
|
77
|
+
amount: number,
|
|
78
|
+
idempotencyKey: string,
|
|
79
|
+
): Promise<unknown> {
|
|
80
|
+
const res = await plasgos.fetch(`/v5/service/payments/${encodeURIComponent(paymentId)}/refunds`, {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
|
|
83
|
+
body: JSON.stringify({ amount: { amount, currency: "IDR" } }),
|
|
84
|
+
});
|
|
85
|
+
if (!res.ok) throw new Error(`Plasgos refunds answered ${String(res.status)}`);
|
|
86
|
+
return res.json();
|
|
87
|
+
}
|
|
88
|
+
// #endregion refund
|
|
89
|
+
|
|
90
|
+
// #region errors
|
|
91
|
+
/** What to do when `getToken()` or `fetch()` rejects. Anything that is not an OidcError is rethrown. */
|
|
92
|
+
export function describeFailure(error: unknown): { retry: boolean; message: string } {
|
|
93
|
+
if (!(error instanceof OidcError)) throw error;
|
|
94
|
+
switch (error.reason) {
|
|
95
|
+
case "unavailable":
|
|
96
|
+
return { retry: true, message: "Plasgos did not answer in time; try again later" };
|
|
97
|
+
case "config_invalid":
|
|
98
|
+
return { retry: false, message: "client id, client secret or scopes are wrong; fix the configuration" };
|
|
99
|
+
case "invalid_target":
|
|
100
|
+
return { retry: false, message: "the resource (audience) is not the one of this environment" };
|
|
101
|
+
default:
|
|
102
|
+
return { retry: false, message: `Plasgos refused the token request (${error.reason})` };
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// #endregion errors
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createSessionStore } from "@plasgos/oidc-client/session";
|
|
2
|
+
import type { SessionSchema, SessionStore } from "@plasgos/oidc-client/session";
|
|
3
|
+
|
|
4
|
+
import { readEnvironment, readSessionSecrets } from "./env.js";
|
|
5
|
+
|
|
6
|
+
// #region app-schema
|
|
7
|
+
/** What this app keeps in its own cookie, next to the SDK's auth. Every field is optional. */
|
|
8
|
+
export interface AppSession {
|
|
9
|
+
flash?: string | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Returns the app data, or null when the cookie does not hold what this app wrote. */
|
|
13
|
+
export const appSchema: SessionSchema<AppSession> = {
|
|
14
|
+
parse(input) {
|
|
15
|
+
if (typeof input !== "object" || input === null) return null;
|
|
16
|
+
const flash: unknown = "flash" in input ? input.flash : undefined;
|
|
17
|
+
if (flash === undefined) return {};
|
|
18
|
+
return typeof flash === "string" && flash.length <= 200 ? { flash } : null;
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
// #endregion app-schema
|
|
22
|
+
|
|
23
|
+
// #region store
|
|
24
|
+
/** Create it once at start. */
|
|
25
|
+
export function createAppSessionStore(): SessionStore<AppSession> {
|
|
26
|
+
return createSessionStore<AppSession>({
|
|
27
|
+
environment: readEnvironment(),
|
|
28
|
+
secrets: readSessionSecrets(),
|
|
29
|
+
// Never change the salt or the names after the first release: the cookie keys are derived from them.
|
|
30
|
+
hkdfSalt: "contoh-app",
|
|
31
|
+
cookies: { app: "ca", auth: "ca-auth", idToken: "ca-idt", transaction: "ca-oidc" },
|
|
32
|
+
authMaxAgeSeconds: 2_592_000,
|
|
33
|
+
appSchema,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
// #endregion store
|
|
37
|
+
|
|
38
|
+
// #region zod-adapter
|
|
39
|
+
/** The part of a zod schema the adapter uses. */
|
|
40
|
+
interface SafeParser<T> {
|
|
41
|
+
safeParse(input: unknown): { success: true; data: T } | { success: false };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Wraps a zod object schema: `appSchema: fromZod(z.object({ flash: z.string().max(200).optional() }))`. */
|
|
45
|
+
export function fromZod<T>(schema: SafeParser<T>): SessionSchema<T> {
|
|
46
|
+
return {
|
|
47
|
+
parse(input) {
|
|
48
|
+
const result = schema.safeParse(input);
|
|
49
|
+
return result.success ? result.data : null;
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
// #endregion zod-adapter
|