@smartcrab/server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/dist/base64.d.ts +14 -0
- package/dist/base64.js +56 -0
- package/dist/cookies.d.ts +33 -0
- package/dist/cookies.js +54 -0
- package/dist/errors.d.ts +86 -0
- package/dist/errors.js +72 -0
- package/dist/http.d.ts +32 -0
- package/dist/http.js +79 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +13 -0
- package/dist/oidc-client.d.ts +36 -0
- package/dist/oidc-client.js +414 -0
- package/dist/result.d.ts +39 -0
- package/dist/result.js +55 -0
- package/dist/sealing.d.ts +7 -0
- package/dist/sealing.js +76 -0
- package/dist/security.d.ts +49 -0
- package/dist/security.js +159 -0
- package/dist/server-auth.d.ts +129 -0
- package/dist/server-auth.js +586 -0
- package/dist/session.d.ts +42 -0
- package/dist/session.js +56 -0
- package/dist/webhook.d.ts +42 -0
- package/dist/webhook.js +95 -0
- package/package.json +44 -0
- package/src/base64.ts +58 -0
- package/src/cookies.ts +72 -0
- package/src/errors.ts +113 -0
- package/src/http.ts +112 -0
- package/src/index.ts +39 -0
- package/src/oidc-client.ts +551 -0
- package/src/result.ts +90 -0
- package/src/sealing.test.ts +57 -0
- package/src/sealing.ts +106 -0
- package/src/security.test.ts +134 -0
- package/src/security.ts +188 -0
- package/src/server-auth.test.ts +1108 -0
- package/src/server-auth.ts +887 -0
- package/src/session.ts +76 -0
- package/src/webhook.test.ts +96 -0
- package/src/webhook.ts +151 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { TokenResponse } from "@smartcrab/contracts-public";
|
|
2
|
+
import type { JWTPayload } from "jose";
|
|
3
|
+
import type { ServerAuthError } from "./errors.js";
|
|
4
|
+
import type { FetchLike } from "./http.js";
|
|
5
|
+
import { type ResultAsync } from "./result.js";
|
|
6
|
+
export interface OidcClientOptions {
|
|
7
|
+
readonly issuer: string;
|
|
8
|
+
readonly clientId: string;
|
|
9
|
+
readonly clientSecret: string;
|
|
10
|
+
readonly fetchImpl: FetchLike;
|
|
11
|
+
}
|
|
12
|
+
export interface AuthorizeUrlInput {
|
|
13
|
+
readonly redirectUri: string;
|
|
14
|
+
readonly scope: string;
|
|
15
|
+
readonly state: string;
|
|
16
|
+
readonly nonce: string;
|
|
17
|
+
readonly codeChallenge: string;
|
|
18
|
+
}
|
|
19
|
+
export interface OidcClient {
|
|
20
|
+
readonly buildAuthorizeUrl: (input: AuthorizeUrlInput) => ResultAsync<string, ServerAuthError>;
|
|
21
|
+
readonly exchangeCode: (input: {
|
|
22
|
+
code: string;
|
|
23
|
+
redirectUri: string;
|
|
24
|
+
codeVerifier: string;
|
|
25
|
+
}) => ResultAsync<TokenResponse, ServerAuthError>;
|
|
26
|
+
readonly refreshTokens: (refreshToken: string) => ResultAsync<TokenResponse, ServerAuthError>;
|
|
27
|
+
readonly revokeRefreshToken: (refreshToken: string) => ResultAsync<void, ServerAuthError>;
|
|
28
|
+
/**
|
|
29
|
+
* `expectedNonce` is `null` for ID tokens returned by the refresh grant
|
|
30
|
+
* (OIDC Core §12.2: nonce is not required there); the login callback always
|
|
31
|
+
* passes the handshake nonce.
|
|
32
|
+
*/
|
|
33
|
+
readonly verifyIdToken: (idToken: string, expectedNonce: string | null) => ResultAsync<JWTPayload, ServerAuthError>;
|
|
34
|
+
readonly verifyAccessToken: (token: string, audience?: string | readonly string[]) => ResultAsync<JWTPayload, ServerAuthError>;
|
|
35
|
+
}
|
|
36
|
+
export declare const createOidcClient: (options: OidcClientOptions) => OidcClient;
|
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { jwksDocumentSchema, oauthErrorResponseSchema, oidcDiscoveryDocumentSchema, tokenResponseSchema, } from "@smartcrab/contracts-public";
|
|
2
|
+
import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from "jose";
|
|
3
|
+
import { DEFAULT_TIMEOUT_MS, basicAuthorizationHeader, fetchBoundedText } from "./http.js";
|
|
4
|
+
import { Result } from "./result.js";
|
|
5
|
+
import { timingSafeEqual } from "./security.js";
|
|
6
|
+
/**
|
|
7
|
+
* OIDC client mechanics for the BFF (design.md §15):
|
|
8
|
+
*
|
|
9
|
+
* - discovery via `<issuer>/.well-known/openid-configuration`, validated by
|
|
10
|
+
* the shared zod contracts and pinned to the configured issuer,
|
|
11
|
+
* - JWKS fetched from the discovered `jwks_uri` (timeout + bounded size),
|
|
12
|
+
* cached, and refetched exactly once when a token references an unknown
|
|
13
|
+
* `kid` (signing-key rotation),
|
|
14
|
+
* - ID token verification with jose: **ES256 only** (unknown `alg` values are
|
|
15
|
+
* rejected before verification), mandatory `kid`, and `iss`/`aud`/`exp`/
|
|
16
|
+
* `typ`/`nonce` all checked (design.md §15.6),
|
|
17
|
+
* - the token endpoint is called with `client_secret_basic` (§15.4 `web_bff`),
|
|
18
|
+
* - OAuth error bodies are parsed into typed errors; `server_error` /
|
|
19
|
+
* `temporarily_unavailable` are marked retryable so callers can honour
|
|
20
|
+
* design.md §21.7 ("一時的ネットワーク障害ではsessionを即削除しない").
|
|
21
|
+
*
|
|
22
|
+
* Every throwing boundary (fetch, JSON.parse, jose) is wrapped exactly once in
|
|
23
|
+
* `Result.fn`; no raw try/catch (design.md §5.2).
|
|
24
|
+
*/
|
|
25
|
+
const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
26
|
+
const JWKS_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
27
|
+
const DISCOVERY_MAX_BYTES = 64 * 1024;
|
|
28
|
+
const JWKS_MAX_BYTES = 256 * 1024;
|
|
29
|
+
const TOKEN_RESPONSE_MAX_BYTES = 64 * 1024;
|
|
30
|
+
const REVOCATION_RESPONSE_MAX_BYTES = 16 * 1024;
|
|
31
|
+
/**
|
|
32
|
+
* `authorization_code` is single-use: aborting the exchange burns the code and
|
|
33
|
+
* the user must log in again. Token issuance (code consumption, session,
|
|
34
|
+
* refresh family, signing) reaches the 5s default, so it gets its own bound.
|
|
35
|
+
*/
|
|
36
|
+
const TOKEN_ENDPOINT_TIMEOUT_MS = 15_000;
|
|
37
|
+
/** Builds a `Result.fn`-wrapped JSON.parse with a call-site-specific error. */
|
|
38
|
+
const jsonParser = (onError) => Result.fn({
|
|
39
|
+
try: async (text) => {
|
|
40
|
+
const parsed = JSON.parse(text);
|
|
41
|
+
return parsed;
|
|
42
|
+
},
|
|
43
|
+
catch: onError,
|
|
44
|
+
});
|
|
45
|
+
/** Maps a jose failure to a static reason string — never the token contents. */
|
|
46
|
+
const joseErrorReason = (cause) => {
|
|
47
|
+
if (typeof cause === "object" &&
|
|
48
|
+
cause !== null &&
|
|
49
|
+
"name" in cause &&
|
|
50
|
+
typeof cause.name === "string") {
|
|
51
|
+
switch (cause.name) {
|
|
52
|
+
case "JWTExpired":
|
|
53
|
+
return "token_expired";
|
|
54
|
+
case "JWSSignatureVerificationFailed":
|
|
55
|
+
return "signature_verification_failed";
|
|
56
|
+
case "JWKSNoMatchingKey":
|
|
57
|
+
return "no_matching_key";
|
|
58
|
+
case "JWKSMultipleMatchingKeys":
|
|
59
|
+
return "multiple_matching_keys";
|
|
60
|
+
case "JWTClaimValidationFailed":
|
|
61
|
+
return "claim_validation_failed";
|
|
62
|
+
case "JWTInvalid":
|
|
63
|
+
return "malformed_token";
|
|
64
|
+
case "JWKSTimeout":
|
|
65
|
+
return "key_fetch_timeout";
|
|
66
|
+
default:
|
|
67
|
+
return "verification_failed";
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return "verification_failed";
|
|
71
|
+
};
|
|
72
|
+
const retryableIfServerError = (status) => status >= 500 ? { retryable: true } : {};
|
|
73
|
+
export const createOidcClient = (options) => {
|
|
74
|
+
const { issuer, clientId, clientSecret, fetchImpl } = options;
|
|
75
|
+
// -------------------------------------------------------------------------
|
|
76
|
+
// Discovery
|
|
77
|
+
// -------------------------------------------------------------------------
|
|
78
|
+
let discoveryCache = null;
|
|
79
|
+
const parseDiscoveryJson = jsonParser(() => ({
|
|
80
|
+
type: "discovery_invalid",
|
|
81
|
+
detail: "invalid_json",
|
|
82
|
+
}));
|
|
83
|
+
const validateDiscovery = async (res) => {
|
|
84
|
+
if (res.status !== 200) {
|
|
85
|
+
const error = {
|
|
86
|
+
type: "discovery_failed",
|
|
87
|
+
status: res.status,
|
|
88
|
+
...retryableIfServerError(res.status),
|
|
89
|
+
};
|
|
90
|
+
return Result.fail(error);
|
|
91
|
+
}
|
|
92
|
+
return Result.andThen(await parseDiscoveryJson(res.body), (json) => {
|
|
93
|
+
const parsed = oidcDiscoveryDocumentSchema.safeParse(json);
|
|
94
|
+
if (!parsed.success) {
|
|
95
|
+
const error = {
|
|
96
|
+
type: "discovery_invalid",
|
|
97
|
+
detail: "schema_validation_failed",
|
|
98
|
+
};
|
|
99
|
+
return Result.fail(error);
|
|
100
|
+
}
|
|
101
|
+
if (parsed.data.issuer !== issuer) {
|
|
102
|
+
const error = { type: "discovery_invalid", detail: "issuer_mismatch" };
|
|
103
|
+
return Result.fail(error);
|
|
104
|
+
}
|
|
105
|
+
return Result.succeed(parsed.data);
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
const getDiscovery = async () => {
|
|
109
|
+
if (discoveryCache !== null && Date.now() - discoveryCache.fetchedAt < DISCOVERY_CACHE_TTL_MS) {
|
|
110
|
+
return Result.succeed(discoveryCache.document);
|
|
111
|
+
}
|
|
112
|
+
const fetched = await fetchBoundedText({
|
|
113
|
+
fetchImpl,
|
|
114
|
+
url: `${issuer}/.well-known/openid-configuration`,
|
|
115
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
116
|
+
maxBytes: DISCOVERY_MAX_BYTES,
|
|
117
|
+
});
|
|
118
|
+
const result = await Result.andThen(fetched, validateDiscovery);
|
|
119
|
+
if (Result.isSuccess(result)) {
|
|
120
|
+
discoveryCache = { fetchedAt: Date.now(), document: result.value };
|
|
121
|
+
}
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
// -------------------------------------------------------------------------
|
|
125
|
+
// JWKS
|
|
126
|
+
// -------------------------------------------------------------------------
|
|
127
|
+
let jwksCache = null;
|
|
128
|
+
const parseJwksJson = jsonParser(() => ({ type: "jwks_invalid", detail: "invalid_json" }));
|
|
129
|
+
const buildLocalKeySet = Result.fn({
|
|
130
|
+
try: async (document) => createLocalJWKSet(document),
|
|
131
|
+
catch: () => ({ type: "jwks_invalid", detail: "key_import_failed" }),
|
|
132
|
+
});
|
|
133
|
+
const fetchAndBuildKeySet = async (jwksUri) => {
|
|
134
|
+
const fetched = await fetchBoundedText({
|
|
135
|
+
fetchImpl,
|
|
136
|
+
url: jwksUri,
|
|
137
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
138
|
+
maxBytes: JWKS_MAX_BYTES,
|
|
139
|
+
});
|
|
140
|
+
return Result.andThen(fetched, async (res) => {
|
|
141
|
+
if (res.status !== 200) {
|
|
142
|
+
const error = {
|
|
143
|
+
type: "jwks_fetch_failed",
|
|
144
|
+
status: res.status,
|
|
145
|
+
...retryableIfServerError(res.status),
|
|
146
|
+
};
|
|
147
|
+
return Result.fail(error);
|
|
148
|
+
}
|
|
149
|
+
const json = await parseJwksJson(res.body);
|
|
150
|
+
return Result.andThen(json, (value) => {
|
|
151
|
+
const parsed = jwksDocumentSchema.safeParse(value);
|
|
152
|
+
if (!parsed.success) {
|
|
153
|
+
const error = {
|
|
154
|
+
type: "jwks_invalid",
|
|
155
|
+
detail: "schema_validation_failed",
|
|
156
|
+
};
|
|
157
|
+
return Result.fail(error);
|
|
158
|
+
}
|
|
159
|
+
return buildLocalKeySet(parsed.data);
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
const getKeySet = async (forceRefresh) => {
|
|
164
|
+
if (!forceRefresh &&
|
|
165
|
+
jwksCache !== null &&
|
|
166
|
+
Date.now() - jwksCache.fetchedAt < JWKS_CACHE_TTL_MS) {
|
|
167
|
+
return Result.succeed(jwksCache.keySet);
|
|
168
|
+
}
|
|
169
|
+
const discovery = await getDiscovery();
|
|
170
|
+
const result = await Result.andThen(discovery, (doc) => fetchAndBuildKeySet(doc.jwks_uri));
|
|
171
|
+
if (Result.isSuccess(result)) {
|
|
172
|
+
jwksCache = { fetchedAt: Date.now(), keySet: result.value };
|
|
173
|
+
}
|
|
174
|
+
return result;
|
|
175
|
+
};
|
|
176
|
+
// -------------------------------------------------------------------------
|
|
177
|
+
// JWT verification
|
|
178
|
+
// -------------------------------------------------------------------------
|
|
179
|
+
const headerDecoder = (onError) => Result.fn({
|
|
180
|
+
try: async (token) => decodeProtectedHeader(token),
|
|
181
|
+
catch: onError,
|
|
182
|
+
});
|
|
183
|
+
const jwtVerifyWrapped = (onError) => Result.fn({
|
|
184
|
+
try: async (input) => {
|
|
185
|
+
const { payload } = await jwtVerify(input.token, input.keySet, {
|
|
186
|
+
issuer,
|
|
187
|
+
...(input.audience !== undefined
|
|
188
|
+
? {
|
|
189
|
+
audience: typeof input.audience === "string" ? input.audience : [...input.audience],
|
|
190
|
+
}
|
|
191
|
+
: {}),
|
|
192
|
+
algorithms: ["ES256"],
|
|
193
|
+
typ: input.typ,
|
|
194
|
+
requiredClaims: [...input.requiredClaims],
|
|
195
|
+
});
|
|
196
|
+
return payload;
|
|
197
|
+
},
|
|
198
|
+
catch: onError,
|
|
199
|
+
});
|
|
200
|
+
/** design.md §15.6: ES256 only, `kid` mandatory — checked before any crypto. */
|
|
201
|
+
const checkHeader = (header, invalidError) => {
|
|
202
|
+
if (header.alg !== "ES256")
|
|
203
|
+
return Result.fail(invalidError("unexpected_alg"));
|
|
204
|
+
if (typeof header.kid !== "string" || header.kid.length === 0) {
|
|
205
|
+
return Result.fail(invalidError("missing_kid"));
|
|
206
|
+
}
|
|
207
|
+
return Result.succeed(header);
|
|
208
|
+
};
|
|
209
|
+
const verifyWithKeySetRetry = async (token, verifyOptions, onError) => {
|
|
210
|
+
const keySetResult = await getKeySet(false);
|
|
211
|
+
if (Result.isFailure(keySetResult))
|
|
212
|
+
return keySetResult;
|
|
213
|
+
const verify = jwtVerifyWrapped(onError);
|
|
214
|
+
const first = await verify({ token, keySet: keySetResult.value, ...verifyOptions });
|
|
215
|
+
if (Result.isSuccess(first))
|
|
216
|
+
return first;
|
|
217
|
+
if ((first.error.type === "id_token_invalid" || first.error.type === "access_token_invalid") &&
|
|
218
|
+
first.error.reason === "no_matching_key") {
|
|
219
|
+
// Unknown kid: the environment may have rotated signing keys. Refetch
|
|
220
|
+
// the JWKS once, then fail closed if the key is still absent.
|
|
221
|
+
const refreshed = await getKeySet(true);
|
|
222
|
+
if (Result.isFailure(refreshed))
|
|
223
|
+
return refreshed;
|
|
224
|
+
return verify({ token, keySet: refreshed.value, ...verifyOptions });
|
|
225
|
+
}
|
|
226
|
+
return first;
|
|
227
|
+
};
|
|
228
|
+
const verifyIdToken = async (idToken, expectedNonce) => {
|
|
229
|
+
const idTokenError = (reason) => ({
|
|
230
|
+
type: "id_token_invalid",
|
|
231
|
+
reason,
|
|
232
|
+
});
|
|
233
|
+
const headerResult = await headerDecoder(() => idTokenError("malformed_token"))(idToken);
|
|
234
|
+
if (Result.isFailure(headerResult))
|
|
235
|
+
return headerResult;
|
|
236
|
+
const checked = checkHeader(headerResult.value, idTokenError);
|
|
237
|
+
if (Result.isFailure(checked))
|
|
238
|
+
return checked;
|
|
239
|
+
const verified = await verifyWithKeySetRetry(idToken, {
|
|
240
|
+
audience: clientId,
|
|
241
|
+
typ: "JWT",
|
|
242
|
+
requiredClaims: expectedNonce !== null ? ["exp", "iat", "sub", "nonce"] : ["exp", "iat", "sub"],
|
|
243
|
+
}, (cause) => idTokenError(joseErrorReason(cause)));
|
|
244
|
+
if (Result.isFailure(verified))
|
|
245
|
+
return verified;
|
|
246
|
+
if (expectedNonce !== null) {
|
|
247
|
+
const nonce = verified.value.nonce;
|
|
248
|
+
if (typeof nonce !== "string" || !timingSafeEqual(nonce, expectedNonce)) {
|
|
249
|
+
return Result.fail(idTokenError("nonce_mismatch"));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return verified;
|
|
253
|
+
};
|
|
254
|
+
const verifyAccessToken = async (token, audience) => {
|
|
255
|
+
const accessTokenError = (reason) => ({
|
|
256
|
+
type: "access_token_invalid",
|
|
257
|
+
reason,
|
|
258
|
+
});
|
|
259
|
+
const headerResult = await headerDecoder(() => accessTokenError("malformed_token"))(token);
|
|
260
|
+
if (Result.isFailure(headerResult))
|
|
261
|
+
return headerResult;
|
|
262
|
+
const checked = checkHeader(headerResult.value, accessTokenError);
|
|
263
|
+
if (Result.isFailure(checked))
|
|
264
|
+
return checked;
|
|
265
|
+
return verifyWithKeySetRetry(token, {
|
|
266
|
+
// design.md §15.6: access tokens carry typ `at+jwt`.
|
|
267
|
+
typ: "at+jwt",
|
|
268
|
+
requiredClaims: ["exp", "iat", "sub"],
|
|
269
|
+
...(audience !== undefined ? { audience } : {}),
|
|
270
|
+
}, (cause) => accessTokenError(joseErrorReason(cause)));
|
|
271
|
+
};
|
|
272
|
+
// -------------------------------------------------------------------------
|
|
273
|
+
// Token endpoint
|
|
274
|
+
// -------------------------------------------------------------------------
|
|
275
|
+
const parseTokenJson = jsonParser(() => ({
|
|
276
|
+
type: "token_response_invalid",
|
|
277
|
+
detail: "invalid_json",
|
|
278
|
+
}));
|
|
279
|
+
const parseTokenResponse = async (res) => {
|
|
280
|
+
const jsonResult = await parseTokenJson(res.body);
|
|
281
|
+
if (Result.isFailure(jsonResult)) {
|
|
282
|
+
if (res.status === 200)
|
|
283
|
+
return jsonResult;
|
|
284
|
+
const error = {
|
|
285
|
+
type: "token_endpoint_failed",
|
|
286
|
+
status: res.status,
|
|
287
|
+
...retryableIfServerError(res.status),
|
|
288
|
+
};
|
|
289
|
+
return Result.fail(error);
|
|
290
|
+
}
|
|
291
|
+
if (res.status === 200) {
|
|
292
|
+
const parsed = tokenResponseSchema.safeParse(jsonResult.value);
|
|
293
|
+
if (!parsed.success) {
|
|
294
|
+
const error = {
|
|
295
|
+
type: "token_response_invalid",
|
|
296
|
+
detail: "schema_validation_failed",
|
|
297
|
+
};
|
|
298
|
+
return Result.fail(error);
|
|
299
|
+
}
|
|
300
|
+
return Result.succeed(parsed.data);
|
|
301
|
+
}
|
|
302
|
+
const parsedError = oauthErrorResponseSchema.safeParse(jsonResult.value);
|
|
303
|
+
if (parsedError.success) {
|
|
304
|
+
const transient = parsedError.data.error === "server_error" ||
|
|
305
|
+
parsedError.data.error === "temporarily_unavailable";
|
|
306
|
+
const error = {
|
|
307
|
+
type: "token_endpoint_rejected",
|
|
308
|
+
code: parsedError.data.error,
|
|
309
|
+
...(transient ? { retryable: true } : {}),
|
|
310
|
+
};
|
|
311
|
+
return Result.fail(error);
|
|
312
|
+
}
|
|
313
|
+
const error = {
|
|
314
|
+
type: "token_endpoint_failed",
|
|
315
|
+
status: res.status,
|
|
316
|
+
...retryableIfServerError(res.status),
|
|
317
|
+
};
|
|
318
|
+
return Result.fail(error);
|
|
319
|
+
};
|
|
320
|
+
const postTokenEndpoint = async (params) => {
|
|
321
|
+
const discovery = await getDiscovery();
|
|
322
|
+
return Result.andThen(discovery, async (doc) => {
|
|
323
|
+
const fetched = await fetchBoundedText({
|
|
324
|
+
fetchImpl,
|
|
325
|
+
url: doc.token_endpoint,
|
|
326
|
+
init: {
|
|
327
|
+
method: "POST",
|
|
328
|
+
headers: {
|
|
329
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
330
|
+
authorization: basicAuthorizationHeader(clientId, clientSecret),
|
|
331
|
+
},
|
|
332
|
+
body: params.toString(),
|
|
333
|
+
},
|
|
334
|
+
timeoutMs: TOKEN_ENDPOINT_TIMEOUT_MS,
|
|
335
|
+
maxBytes: TOKEN_RESPONSE_MAX_BYTES,
|
|
336
|
+
});
|
|
337
|
+
return Result.andThen(fetched, parseTokenResponse);
|
|
338
|
+
});
|
|
339
|
+
};
|
|
340
|
+
const exchangeCode = (input) => {
|
|
341
|
+
const params = new URLSearchParams();
|
|
342
|
+
params.set("grant_type", "authorization_code");
|
|
343
|
+
params.set("code", input.code);
|
|
344
|
+
params.set("redirect_uri", input.redirectUri);
|
|
345
|
+
params.set("code_verifier", input.codeVerifier);
|
|
346
|
+
return postTokenEndpoint(params);
|
|
347
|
+
};
|
|
348
|
+
const refreshTokens = (refreshToken) => {
|
|
349
|
+
const params = new URLSearchParams();
|
|
350
|
+
params.set("grant_type", "refresh_token");
|
|
351
|
+
params.set("refresh_token", refreshToken);
|
|
352
|
+
return postTokenEndpoint(params);
|
|
353
|
+
};
|
|
354
|
+
const revokeRefreshToken = async (refreshToken) => {
|
|
355
|
+
const discovery = await getDiscovery();
|
|
356
|
+
return Result.andThen(discovery, async (doc) => {
|
|
357
|
+
const params = new URLSearchParams();
|
|
358
|
+
params.set("token", refreshToken);
|
|
359
|
+
params.set("token_type_hint", "refresh_token");
|
|
360
|
+
const fetched = await fetchBoundedText({
|
|
361
|
+
fetchImpl,
|
|
362
|
+
url: doc.revocation_endpoint,
|
|
363
|
+
init: {
|
|
364
|
+
method: "POST",
|
|
365
|
+
headers: {
|
|
366
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
367
|
+
authorization: basicAuthorizationHeader(clientId, clientSecret),
|
|
368
|
+
},
|
|
369
|
+
body: params.toString(),
|
|
370
|
+
},
|
|
371
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
372
|
+
maxBytes: REVOCATION_RESPONSE_MAX_BYTES,
|
|
373
|
+
});
|
|
374
|
+
// design.md §15.8: the endpoint returns 200 even for tokens that never
|
|
375
|
+
// existed, so any 2xx is success; the caller (logout) treats the rest
|
|
376
|
+
// as best-effort.
|
|
377
|
+
return Result.andThen(fetched, (res) => {
|
|
378
|
+
if (res.status >= 200 && res.status < 300)
|
|
379
|
+
return Result.succeed(undefined);
|
|
380
|
+
const error = {
|
|
381
|
+
type: "revocation_failed",
|
|
382
|
+
status: res.status,
|
|
383
|
+
...retryableIfServerError(res.status),
|
|
384
|
+
};
|
|
385
|
+
return Result.fail(error);
|
|
386
|
+
});
|
|
387
|
+
});
|
|
388
|
+
};
|
|
389
|
+
// -------------------------------------------------------------------------
|
|
390
|
+
// Authorize redirect
|
|
391
|
+
// -------------------------------------------------------------------------
|
|
392
|
+
const buildAuthorizeUrl = (input) => Result.mapAsync(getDiscovery(), (doc) => {
|
|
393
|
+
// `authorization_endpoint` is a schema-validated https URL, so `new URL`
|
|
394
|
+
// cannot throw here.
|
|
395
|
+
const url = new URL(doc.authorization_endpoint);
|
|
396
|
+
url.searchParams.set("response_type", "code");
|
|
397
|
+
url.searchParams.set("client_id", clientId);
|
|
398
|
+
url.searchParams.set("redirect_uri", input.redirectUri);
|
|
399
|
+
url.searchParams.set("scope", input.scope);
|
|
400
|
+
url.searchParams.set("state", input.state);
|
|
401
|
+
url.searchParams.set("nonce", input.nonce);
|
|
402
|
+
url.searchParams.set("code_challenge", input.codeChallenge);
|
|
403
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
404
|
+
return url.toString();
|
|
405
|
+
});
|
|
406
|
+
return {
|
|
407
|
+
buildAuthorizeUrl,
|
|
408
|
+
exchangeCode,
|
|
409
|
+
refreshTokens,
|
|
410
|
+
revokeRefreshToken,
|
|
411
|
+
verifyIdToken,
|
|
412
|
+
verifyAccessToken,
|
|
413
|
+
};
|
|
414
|
+
};
|
package/dist/result.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Result implementation for @smartcrab/server.
|
|
3
|
+
*
|
|
4
|
+
* `@praha/byethrow` / `@smartcrab/result` are intentionally NOT
|
|
5
|
+
* dependencies of this publishable SDK (package.json is limited to `jose`,
|
|
6
|
+
* `cookie` and `@smartcrab/contracts-public`; the repo rules forbid adding
|
|
7
|
+
* dependencies), so this module provides the small byethrow-compatible subset
|
|
8
|
+
* the SDK needs. The semantics follow design.md §5.2: exception-able
|
|
9
|
+
* boundaries (fetch, WebCrypto, jose, JSON.parse) are wrapped exactly once by
|
|
10
|
+
* `Result.fn`, every error is a typed union member, and no code in this
|
|
11
|
+
* package uses a raw `try { } catch { }` — even `fn` below converts throws
|
|
12
|
+
* through the promise-rejection channel instead of try/catch.
|
|
13
|
+
*/
|
|
14
|
+
export type Success<T> = {
|
|
15
|
+
readonly type: "Success";
|
|
16
|
+
readonly value: T;
|
|
17
|
+
};
|
|
18
|
+
export type Failure<E> = {
|
|
19
|
+
readonly type: "Failure";
|
|
20
|
+
readonly error: E;
|
|
21
|
+
};
|
|
22
|
+
export type Result<T, E> = Success<T> | Failure<E>;
|
|
23
|
+
export type ResultAsync<T, E> = Promise<Result<T, E>>;
|
|
24
|
+
export type ResultMaybeAsync<T, E> = Result<T, E> | ResultAsync<T, E>;
|
|
25
|
+
export declare const Result: {
|
|
26
|
+
readonly succeed: <T>(value: T) => Success<T>;
|
|
27
|
+
readonly fail: <E>(error: E) => Failure<E>;
|
|
28
|
+
readonly isSuccess: <T, E>(result: Result<T, E>) => result is Success<T>;
|
|
29
|
+
readonly isFailure: <T, E>(result: Result<T, E>) => result is Failure<E>;
|
|
30
|
+
readonly map: <T, U, E>(result: Result<T, E>, f: (value: T) => U) => Result<U, E>;
|
|
31
|
+
readonly mapAsync: <T, U, E>(result: ResultMaybeAsync<T, E>, f: (value: T) => U | Promise<U>) => ResultAsync<U, E>;
|
|
32
|
+
readonly mapError: <T, E, F>(result: Result<T, E>, f: (error: E) => F) => Result<T, F>;
|
|
33
|
+
readonly andThen: <T, U, E>(result: ResultMaybeAsync<T, E>, f: (value: T) => ResultMaybeAsync<U, E>) => ResultAsync<U, E>;
|
|
34
|
+
readonly orElse: <T, E, F>(result: ResultMaybeAsync<T, E>, f: (error: E) => ResultMaybeAsync<T, F>) => ResultAsync<T, F>;
|
|
35
|
+
readonly fn: <A extends readonly unknown[], T, E>(options: {
|
|
36
|
+
readonly try: (...args: A) => Promise<T>;
|
|
37
|
+
readonly catch: (cause: unknown) => E;
|
|
38
|
+
}) => ((...args: A) => ResultAsync<T, E>);
|
|
39
|
+
};
|
package/dist/result.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Result implementation for @smartcrab/server.
|
|
3
|
+
*
|
|
4
|
+
* `@praha/byethrow` / `@smartcrab/result` are intentionally NOT
|
|
5
|
+
* dependencies of this publishable SDK (package.json is limited to `jose`,
|
|
6
|
+
* `cookie` and `@smartcrab/contracts-public`; the repo rules forbid adding
|
|
7
|
+
* dependencies), so this module provides the small byethrow-compatible subset
|
|
8
|
+
* the SDK needs. The semantics follow design.md §5.2: exception-able
|
|
9
|
+
* boundaries (fetch, WebCrypto, jose, JSON.parse) are wrapped exactly once by
|
|
10
|
+
* `Result.fn`, every error is a typed union member, and no code in this
|
|
11
|
+
* package uses a raw `try { } catch { }` — even `fn` below converts throws
|
|
12
|
+
* through the promise-rejection channel instead of try/catch.
|
|
13
|
+
*/
|
|
14
|
+
const succeed = (value) => ({ type: "Success", value });
|
|
15
|
+
const fail = (error) => ({ type: "Failure", error });
|
|
16
|
+
const isSuccess = (result) => result.type === "Success";
|
|
17
|
+
const isFailure = (result) => result.type === "Failure";
|
|
18
|
+
const map = (result, f) => isSuccess(result) ? succeed(f(result.value)) : result;
|
|
19
|
+
const mapAsync = async (result, f) => {
|
|
20
|
+
const resolved = await result;
|
|
21
|
+
return isSuccess(resolved) ? succeed(await f(resolved.value)) : resolved;
|
|
22
|
+
};
|
|
23
|
+
const mapError = (result, f) => isFailure(result) ? fail(f(result.error)) : result;
|
|
24
|
+
const andThen = async (result, f) => {
|
|
25
|
+
const resolved = await result;
|
|
26
|
+
return isSuccess(resolved) ? f(resolved.value) : resolved;
|
|
27
|
+
};
|
|
28
|
+
const orElse = async (result, f) => {
|
|
29
|
+
const resolved = await result;
|
|
30
|
+
return isFailure(resolved) ? f(resolved.error) : resolved;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Wraps a throwing/rejecting boundary exactly once (design.md §5.2). `try`
|
|
34
|
+
* must be an async function; a synchronous throw inside it becomes a promise
|
|
35
|
+
* rejection and is converted by the same `catch` mapper, so callers never see
|
|
36
|
+
* an exception cross the boundary. The `catch` mapper receives `unknown` and
|
|
37
|
+
* must produce a typed error without unvalidated casts.
|
|
38
|
+
*/
|
|
39
|
+
const fn = (options) => {
|
|
40
|
+
return (...args) => Promise.resolve()
|
|
41
|
+
.then(() => options.try(...args))
|
|
42
|
+
.then((value) => succeed(value), (cause) => fail(options.catch(cause)));
|
|
43
|
+
};
|
|
44
|
+
export const Result = {
|
|
45
|
+
succeed,
|
|
46
|
+
fail,
|
|
47
|
+
isSuccess,
|
|
48
|
+
isFailure,
|
|
49
|
+
map,
|
|
50
|
+
mapAsync,
|
|
51
|
+
mapError,
|
|
52
|
+
andThen,
|
|
53
|
+
orElse,
|
|
54
|
+
fn,
|
|
55
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ServerAuthError } from "./errors.js";
|
|
2
|
+
import { type ResultAsync } from "./result.js";
|
|
3
|
+
export interface Sealer {
|
|
4
|
+
readonly seal: (payload: unknown) => ResultAsync<string, ServerAuthError>;
|
|
5
|
+
readonly unseal: (value: string) => ResultAsync<unknown, ServerAuthError>;
|
|
6
|
+
}
|
|
7
|
+
export declare const createSealer: (secret: string) => Sealer;
|
package/dist/sealing.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { base64UrlDecode, base64UrlEncode } from "./base64.js";
|
|
2
|
+
import { Result } from "./result.js";
|
|
3
|
+
/**
|
|
4
|
+
* Session-value sealing (design.md §22.2 "HttpOnly Cookie管理").
|
|
5
|
+
*
|
|
6
|
+
* Chosen design (the assignment offered HMAC-signed payloads or a server-side
|
|
7
|
+
* store reference): the cookie value is an **AES-256-GCM encrypted** payload
|
|
8
|
+
* with a per-config key derived from `cookieSecret` via HKDF-SHA-256. This
|
|
9
|
+
* makes the value both opaque (confidential — access/refresh tokens never
|
|
10
|
+
* appear in the clear to the browser or to log scrapers) and
|
|
11
|
+
* integrity-protected (GCM's auth tag: any tampering fails decryption, and the
|
|
12
|
+
* SDK fails closed by treating the cookie as absent/invalid). A server-side
|
|
13
|
+
* session store was rejected to keep the BFF stateless across Workers
|
|
14
|
+
* isolates; rotation handling lives in the in-process refresh mutex instead
|
|
15
|
+
* (see server-auth.ts).
|
|
16
|
+
*
|
|
17
|
+
* Wire format: `v1.<base64url(iv)> . <base64url(ciphertext||tag)>`.
|
|
18
|
+
* The `v1` prefix allows future algorithm rotation; any other shape is
|
|
19
|
+
* rejected before touching WebCrypto.
|
|
20
|
+
*/
|
|
21
|
+
const SEAL_VERSION = "v1";
|
|
22
|
+
const GCM_IV_BYTES = 12;
|
|
23
|
+
const textEncoder = new TextEncoder();
|
|
24
|
+
const textDecoder = new TextDecoder();
|
|
25
|
+
const HKDF_SALT = textEncoder.encode("@smartcrab/server/session-seal/v1");
|
|
26
|
+
const HKDF_INFO = textEncoder.encode("aes-256-gcm cookie seal");
|
|
27
|
+
const importKeyMaterial = Result.fn({
|
|
28
|
+
try: async (secret) => crypto.subtle.importKey("raw", textEncoder.encode(secret), "HKDF", false, ["deriveKey"]),
|
|
29
|
+
catch: () => ({ type: "sealing_failed" }),
|
|
30
|
+
});
|
|
31
|
+
const deriveAesKey = Result.fn({
|
|
32
|
+
try: async (material) => crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: HKDF_SALT, info: HKDF_INFO }, material, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]),
|
|
33
|
+
catch: () => ({ type: "sealing_failed" }),
|
|
34
|
+
});
|
|
35
|
+
const encrypt = Result.fn({
|
|
36
|
+
try: async (input) => {
|
|
37
|
+
const iv = new Uint8Array(GCM_IV_BYTES);
|
|
38
|
+
crypto.getRandomValues(iv);
|
|
39
|
+
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, input.key, textEncoder.encode(JSON.stringify(input.payload)));
|
|
40
|
+
return `${SEAL_VERSION}.${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(ciphertext))}`;
|
|
41
|
+
},
|
|
42
|
+
catch: () => ({ type: "sealing_failed" }),
|
|
43
|
+
});
|
|
44
|
+
const decrypt = Result.fn({
|
|
45
|
+
try: async (input) => {
|
|
46
|
+
const [version, ivPart, ciphertextPart, ...rest] = input.value.split(".");
|
|
47
|
+
if (version !== SEAL_VERSION ||
|
|
48
|
+
ivPart === undefined ||
|
|
49
|
+
ciphertextPart === undefined ||
|
|
50
|
+
rest.length > 0) {
|
|
51
|
+
throw new Error("malformed sealed value");
|
|
52
|
+
}
|
|
53
|
+
const iv = base64UrlDecode(ivPart);
|
|
54
|
+
const ciphertext = base64UrlDecode(ciphertextPart);
|
|
55
|
+
if (iv.byteLength !== GCM_IV_BYTES) {
|
|
56
|
+
throw new Error("malformed sealed value");
|
|
57
|
+
}
|
|
58
|
+
const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, input.key, ciphertext);
|
|
59
|
+
const parsed = JSON.parse(textDecoder.decode(plaintext));
|
|
60
|
+
return parsed;
|
|
61
|
+
},
|
|
62
|
+
catch: () => ({ type: "seal_verification_failed" }),
|
|
63
|
+
});
|
|
64
|
+
export const createSealer = (secret) => {
|
|
65
|
+
// The HKDF derivation is deterministic per secret; cache the derived key so
|
|
66
|
+
// the hot path (every authenticated request) does one AES-GCM operation only.
|
|
67
|
+
let cachedKey = null;
|
|
68
|
+
const key = () => {
|
|
69
|
+
cachedKey ??= Result.andThen(importKeyMaterial(secret), deriveAesKey);
|
|
70
|
+
return cachedKey;
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
seal: (payload) => Result.andThen(key(), (aesKey) => encrypt({ key: aesKey, payload })),
|
|
74
|
+
unseal: (value) => Result.andThen(key(), (aesKey) => decrypt({ key: aesKey, value })),
|
|
75
|
+
};
|
|
76
|
+
};
|