@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,551 @@
|
|
|
1
|
+
import {
|
|
2
|
+
jwksDocumentSchema,
|
|
3
|
+
oauthErrorResponseSchema,
|
|
4
|
+
oidcDiscoveryDocumentSchema,
|
|
5
|
+
tokenResponseSchema,
|
|
6
|
+
} from "@smartcrab/contracts-public";
|
|
7
|
+
import type {
|
|
8
|
+
JwksDocument,
|
|
9
|
+
OidcDiscoveryDocument,
|
|
10
|
+
TokenResponse,
|
|
11
|
+
} from "@smartcrab/contracts-public";
|
|
12
|
+
import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from "jose";
|
|
13
|
+
import type { JWTPayload, LocalJWKSet, ProtectedHeaderParameters } from "jose";
|
|
14
|
+
import type { ServerAuthError } from "./errors.js";
|
|
15
|
+
import { DEFAULT_TIMEOUT_MS, basicAuthorizationHeader, fetchBoundedText } from "./http.js";
|
|
16
|
+
import type { FetchLike, FetchedText } from "./http.js";
|
|
17
|
+
import { Result, type ResultAsync } from "./result.js";
|
|
18
|
+
import { timingSafeEqual } from "./security.js";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* OIDC client mechanics for the BFF (design.md §15):
|
|
22
|
+
*
|
|
23
|
+
* - discovery via `<issuer>/.well-known/openid-configuration`, validated by
|
|
24
|
+
* the shared zod contracts and pinned to the configured issuer,
|
|
25
|
+
* - JWKS fetched from the discovered `jwks_uri` (timeout + bounded size),
|
|
26
|
+
* cached, and refetched exactly once when a token references an unknown
|
|
27
|
+
* `kid` (signing-key rotation),
|
|
28
|
+
* - ID token verification with jose: **ES256 only** (unknown `alg` values are
|
|
29
|
+
* rejected before verification), mandatory `kid`, and `iss`/`aud`/`exp`/
|
|
30
|
+
* `typ`/`nonce` all checked (design.md §15.6),
|
|
31
|
+
* - the token endpoint is called with `client_secret_basic` (§15.4 `web_bff`),
|
|
32
|
+
* - OAuth error bodies are parsed into typed errors; `server_error` /
|
|
33
|
+
* `temporarily_unavailable` are marked retryable so callers can honour
|
|
34
|
+
* design.md §21.7 ("一時的ネットワーク障害ではsessionを即削除しない").
|
|
35
|
+
*
|
|
36
|
+
* Every throwing boundary (fetch, JSON.parse, jose) is wrapped exactly once in
|
|
37
|
+
* `Result.fn`; no raw try/catch (design.md §5.2).
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
const DISCOVERY_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
41
|
+
const JWKS_CACHE_TTL_MS = 60 * 60 * 1000;
|
|
42
|
+
const DISCOVERY_MAX_BYTES = 64 * 1024;
|
|
43
|
+
const JWKS_MAX_BYTES = 256 * 1024;
|
|
44
|
+
const TOKEN_RESPONSE_MAX_BYTES = 64 * 1024;
|
|
45
|
+
const REVOCATION_RESPONSE_MAX_BYTES = 16 * 1024;
|
|
46
|
+
/**
|
|
47
|
+
* `authorization_code` is single-use: aborting the exchange burns the code and
|
|
48
|
+
* the user must log in again. Token issuance (code consumption, session,
|
|
49
|
+
* refresh family, signing) reaches the 5s default, so it gets its own bound.
|
|
50
|
+
*/
|
|
51
|
+
const TOKEN_ENDPOINT_TIMEOUT_MS = 15_000;
|
|
52
|
+
|
|
53
|
+
export interface OidcClientOptions {
|
|
54
|
+
readonly issuer: string;
|
|
55
|
+
readonly clientId: string;
|
|
56
|
+
readonly clientSecret: string;
|
|
57
|
+
readonly fetchImpl: FetchLike;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface AuthorizeUrlInput {
|
|
61
|
+
readonly redirectUri: string;
|
|
62
|
+
readonly scope: string;
|
|
63
|
+
readonly state: string;
|
|
64
|
+
readonly nonce: string;
|
|
65
|
+
readonly codeChallenge: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface OidcClient {
|
|
69
|
+
readonly buildAuthorizeUrl: (input: AuthorizeUrlInput) => ResultAsync<string, ServerAuthError>;
|
|
70
|
+
readonly exchangeCode: (input: {
|
|
71
|
+
code: string;
|
|
72
|
+
redirectUri: string;
|
|
73
|
+
codeVerifier: string;
|
|
74
|
+
}) => ResultAsync<TokenResponse, ServerAuthError>;
|
|
75
|
+
readonly refreshTokens: (refreshToken: string) => ResultAsync<TokenResponse, ServerAuthError>;
|
|
76
|
+
readonly revokeRefreshToken: (refreshToken: string) => ResultAsync<void, ServerAuthError>;
|
|
77
|
+
/**
|
|
78
|
+
* `expectedNonce` is `null` for ID tokens returned by the refresh grant
|
|
79
|
+
* (OIDC Core §12.2: nonce is not required there); the login callback always
|
|
80
|
+
* passes the handshake nonce.
|
|
81
|
+
*/
|
|
82
|
+
readonly verifyIdToken: (
|
|
83
|
+
idToken: string,
|
|
84
|
+
expectedNonce: string | null,
|
|
85
|
+
) => ResultAsync<JWTPayload, ServerAuthError>;
|
|
86
|
+
readonly verifyAccessToken: (
|
|
87
|
+
token: string,
|
|
88
|
+
audience?: string | readonly string[],
|
|
89
|
+
) => ResultAsync<JWTPayload, ServerAuthError>;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Builds a `Result.fn`-wrapped JSON.parse with a call-site-specific error. */
|
|
93
|
+
const jsonParser = (onError: () => ServerAuthError) =>
|
|
94
|
+
Result.fn({
|
|
95
|
+
try: async (text: string): Promise<unknown> => {
|
|
96
|
+
const parsed: unknown = JSON.parse(text);
|
|
97
|
+
return parsed;
|
|
98
|
+
},
|
|
99
|
+
catch: onError,
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
/** Maps a jose failure to a static reason string — never the token contents. */
|
|
103
|
+
const joseErrorReason = (cause: unknown): string => {
|
|
104
|
+
if (
|
|
105
|
+
typeof cause === "object" &&
|
|
106
|
+
cause !== null &&
|
|
107
|
+
"name" in cause &&
|
|
108
|
+
typeof cause.name === "string"
|
|
109
|
+
) {
|
|
110
|
+
switch (cause.name) {
|
|
111
|
+
case "JWTExpired":
|
|
112
|
+
return "token_expired";
|
|
113
|
+
case "JWSSignatureVerificationFailed":
|
|
114
|
+
return "signature_verification_failed";
|
|
115
|
+
case "JWKSNoMatchingKey":
|
|
116
|
+
return "no_matching_key";
|
|
117
|
+
case "JWKSMultipleMatchingKeys":
|
|
118
|
+
return "multiple_matching_keys";
|
|
119
|
+
case "JWTClaimValidationFailed":
|
|
120
|
+
return "claim_validation_failed";
|
|
121
|
+
case "JWTInvalid":
|
|
122
|
+
return "malformed_token";
|
|
123
|
+
case "JWKSTimeout":
|
|
124
|
+
return "key_fetch_timeout";
|
|
125
|
+
default:
|
|
126
|
+
return "verification_failed";
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return "verification_failed";
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const retryableIfServerError = (
|
|
133
|
+
status: number,
|
|
134
|
+
): { readonly retryable: true } | Record<string, never> =>
|
|
135
|
+
status >= 500 ? { retryable: true } : {};
|
|
136
|
+
|
|
137
|
+
export const createOidcClient = (options: OidcClientOptions): OidcClient => {
|
|
138
|
+
const { issuer, clientId, clientSecret, fetchImpl } = options;
|
|
139
|
+
|
|
140
|
+
// -------------------------------------------------------------------------
|
|
141
|
+
// Discovery
|
|
142
|
+
// -------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
let discoveryCache: {
|
|
145
|
+
readonly fetchedAt: number;
|
|
146
|
+
readonly document: OidcDiscoveryDocument;
|
|
147
|
+
} | null = null;
|
|
148
|
+
|
|
149
|
+
const parseDiscoveryJson = jsonParser(() => ({
|
|
150
|
+
type: "discovery_invalid",
|
|
151
|
+
detail: "invalid_json",
|
|
152
|
+
}));
|
|
153
|
+
|
|
154
|
+
const validateDiscovery = async (
|
|
155
|
+
res: FetchedText,
|
|
156
|
+
): ResultAsync<OidcDiscoveryDocument, ServerAuthError> => {
|
|
157
|
+
if (res.status !== 200) {
|
|
158
|
+
const error: ServerAuthError = {
|
|
159
|
+
type: "discovery_failed",
|
|
160
|
+
status: res.status,
|
|
161
|
+
...retryableIfServerError(res.status),
|
|
162
|
+
};
|
|
163
|
+
return Result.fail(error);
|
|
164
|
+
}
|
|
165
|
+
return Result.andThen(await parseDiscoveryJson(res.body), (json) => {
|
|
166
|
+
const parsed = oidcDiscoveryDocumentSchema.safeParse(json);
|
|
167
|
+
if (!parsed.success) {
|
|
168
|
+
const error: ServerAuthError = {
|
|
169
|
+
type: "discovery_invalid",
|
|
170
|
+
detail: "schema_validation_failed",
|
|
171
|
+
};
|
|
172
|
+
return Result.fail(error);
|
|
173
|
+
}
|
|
174
|
+
if (parsed.data.issuer !== issuer) {
|
|
175
|
+
const error: ServerAuthError = { type: "discovery_invalid", detail: "issuer_mismatch" };
|
|
176
|
+
return Result.fail(error);
|
|
177
|
+
}
|
|
178
|
+
return Result.succeed(parsed.data);
|
|
179
|
+
});
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const getDiscovery = async (): ResultAsync<OidcDiscoveryDocument, ServerAuthError> => {
|
|
183
|
+
if (discoveryCache !== null && Date.now() - discoveryCache.fetchedAt < DISCOVERY_CACHE_TTL_MS) {
|
|
184
|
+
return Result.succeed(discoveryCache.document);
|
|
185
|
+
}
|
|
186
|
+
const fetched = await fetchBoundedText({
|
|
187
|
+
fetchImpl,
|
|
188
|
+
url: `${issuer}/.well-known/openid-configuration`,
|
|
189
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
190
|
+
maxBytes: DISCOVERY_MAX_BYTES,
|
|
191
|
+
});
|
|
192
|
+
const result = await Result.andThen(fetched, validateDiscovery);
|
|
193
|
+
if (Result.isSuccess(result)) {
|
|
194
|
+
discoveryCache = { fetchedAt: Date.now(), document: result.value };
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// -------------------------------------------------------------------------
|
|
200
|
+
// JWKS
|
|
201
|
+
// -------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
let jwksCache: { readonly fetchedAt: number; readonly keySet: LocalJWKSet } | null = null;
|
|
204
|
+
|
|
205
|
+
const parseJwksJson = jsonParser(() => ({ type: "jwks_invalid", detail: "invalid_json" }));
|
|
206
|
+
|
|
207
|
+
const buildLocalKeySet = Result.fn({
|
|
208
|
+
try: async (document: JwksDocument): Promise<LocalJWKSet> => createLocalJWKSet(document),
|
|
209
|
+
catch: (): ServerAuthError => ({ type: "jwks_invalid", detail: "key_import_failed" }),
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const fetchAndBuildKeySet = async (
|
|
213
|
+
jwksUri: string,
|
|
214
|
+
): ResultAsync<LocalJWKSet, ServerAuthError> => {
|
|
215
|
+
const fetched = await fetchBoundedText({
|
|
216
|
+
fetchImpl,
|
|
217
|
+
url: jwksUri,
|
|
218
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
219
|
+
maxBytes: JWKS_MAX_BYTES,
|
|
220
|
+
});
|
|
221
|
+
return Result.andThen(fetched, async (res): ResultAsync<LocalJWKSet, ServerAuthError> => {
|
|
222
|
+
if (res.status !== 200) {
|
|
223
|
+
const error: ServerAuthError = {
|
|
224
|
+
type: "jwks_fetch_failed",
|
|
225
|
+
status: res.status,
|
|
226
|
+
...retryableIfServerError(res.status),
|
|
227
|
+
};
|
|
228
|
+
return Result.fail(error);
|
|
229
|
+
}
|
|
230
|
+
const json = await parseJwksJson(res.body);
|
|
231
|
+
return Result.andThen(json, (value) => {
|
|
232
|
+
const parsed = jwksDocumentSchema.safeParse(value);
|
|
233
|
+
if (!parsed.success) {
|
|
234
|
+
const error: ServerAuthError = {
|
|
235
|
+
type: "jwks_invalid",
|
|
236
|
+
detail: "schema_validation_failed",
|
|
237
|
+
};
|
|
238
|
+
return Result.fail(error);
|
|
239
|
+
}
|
|
240
|
+
return buildLocalKeySet(parsed.data);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const getKeySet = async (forceRefresh: boolean): ResultAsync<LocalJWKSet, ServerAuthError> => {
|
|
246
|
+
if (
|
|
247
|
+
!forceRefresh &&
|
|
248
|
+
jwksCache !== null &&
|
|
249
|
+
Date.now() - jwksCache.fetchedAt < JWKS_CACHE_TTL_MS
|
|
250
|
+
) {
|
|
251
|
+
return Result.succeed(jwksCache.keySet);
|
|
252
|
+
}
|
|
253
|
+
const discovery = await getDiscovery();
|
|
254
|
+
const result = await Result.andThen(discovery, (doc) => fetchAndBuildKeySet(doc.jwks_uri));
|
|
255
|
+
if (Result.isSuccess(result)) {
|
|
256
|
+
jwksCache = { fetchedAt: Date.now(), keySet: result.value };
|
|
257
|
+
}
|
|
258
|
+
return result;
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// -------------------------------------------------------------------------
|
|
262
|
+
// JWT verification
|
|
263
|
+
// -------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
const headerDecoder = (onError: () => ServerAuthError) =>
|
|
266
|
+
Result.fn({
|
|
267
|
+
try: async (token: string): Promise<ProtectedHeaderParameters> =>
|
|
268
|
+
decodeProtectedHeader(token),
|
|
269
|
+
catch: onError,
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
const jwtVerifyWrapped = (onError: (cause: unknown) => ServerAuthError) =>
|
|
273
|
+
Result.fn({
|
|
274
|
+
try: async (input: {
|
|
275
|
+
readonly token: string;
|
|
276
|
+
readonly keySet: LocalJWKSet;
|
|
277
|
+
readonly audience?: string | readonly string[];
|
|
278
|
+
readonly typ: string;
|
|
279
|
+
readonly requiredClaims: readonly string[];
|
|
280
|
+
}): Promise<JWTPayload> => {
|
|
281
|
+
const { payload } = await jwtVerify(input.token, input.keySet, {
|
|
282
|
+
issuer,
|
|
283
|
+
...(input.audience !== undefined
|
|
284
|
+
? {
|
|
285
|
+
audience: typeof input.audience === "string" ? input.audience : [...input.audience],
|
|
286
|
+
}
|
|
287
|
+
: {}),
|
|
288
|
+
algorithms: ["ES256"],
|
|
289
|
+
typ: input.typ,
|
|
290
|
+
requiredClaims: [...input.requiredClaims],
|
|
291
|
+
});
|
|
292
|
+
return payload;
|
|
293
|
+
},
|
|
294
|
+
catch: onError,
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
/** design.md §15.6: ES256 only, `kid` mandatory — checked before any crypto. */
|
|
298
|
+
const checkHeader = (
|
|
299
|
+
header: ProtectedHeaderParameters,
|
|
300
|
+
invalidError: (reason: string) => ServerAuthError,
|
|
301
|
+
): Result<ProtectedHeaderParameters, ServerAuthError> => {
|
|
302
|
+
if (header.alg !== "ES256") return Result.fail(invalidError("unexpected_alg"));
|
|
303
|
+
if (typeof header.kid !== "string" || header.kid.length === 0) {
|
|
304
|
+
return Result.fail(invalidError("missing_kid"));
|
|
305
|
+
}
|
|
306
|
+
return Result.succeed(header);
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const verifyWithKeySetRetry = async (
|
|
310
|
+
token: string,
|
|
311
|
+
verifyOptions: {
|
|
312
|
+
readonly audience?: string | readonly string[];
|
|
313
|
+
readonly typ: string;
|
|
314
|
+
readonly requiredClaims: readonly string[];
|
|
315
|
+
},
|
|
316
|
+
onError: (cause: unknown) => ServerAuthError,
|
|
317
|
+
): ResultAsync<JWTPayload, ServerAuthError> => {
|
|
318
|
+
const keySetResult = await getKeySet(false);
|
|
319
|
+
if (Result.isFailure(keySetResult)) return keySetResult;
|
|
320
|
+
const verify = jwtVerifyWrapped(onError);
|
|
321
|
+
const first = await verify({ token, keySet: keySetResult.value, ...verifyOptions });
|
|
322
|
+
if (Result.isSuccess(first)) return first;
|
|
323
|
+
if (
|
|
324
|
+
(first.error.type === "id_token_invalid" || first.error.type === "access_token_invalid") &&
|
|
325
|
+
first.error.reason === "no_matching_key"
|
|
326
|
+
) {
|
|
327
|
+
// Unknown kid: the environment may have rotated signing keys. Refetch
|
|
328
|
+
// the JWKS once, then fail closed if the key is still absent.
|
|
329
|
+
const refreshed = await getKeySet(true);
|
|
330
|
+
if (Result.isFailure(refreshed)) return refreshed;
|
|
331
|
+
return verify({ token, keySet: refreshed.value, ...verifyOptions });
|
|
332
|
+
}
|
|
333
|
+
return first;
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
const verifyIdToken = async (
|
|
337
|
+
idToken: string,
|
|
338
|
+
expectedNonce: string | null,
|
|
339
|
+
): ResultAsync<JWTPayload, ServerAuthError> => {
|
|
340
|
+
const idTokenError = (reason: string): ServerAuthError => ({
|
|
341
|
+
type: "id_token_invalid",
|
|
342
|
+
reason,
|
|
343
|
+
});
|
|
344
|
+
const headerResult = await headerDecoder(() => idTokenError("malformed_token"))(idToken);
|
|
345
|
+
if (Result.isFailure(headerResult)) return headerResult;
|
|
346
|
+
const checked = checkHeader(headerResult.value, idTokenError);
|
|
347
|
+
if (Result.isFailure(checked)) return checked;
|
|
348
|
+
const verified = await verifyWithKeySetRetry(
|
|
349
|
+
idToken,
|
|
350
|
+
{
|
|
351
|
+
audience: clientId,
|
|
352
|
+
typ: "JWT",
|
|
353
|
+
requiredClaims:
|
|
354
|
+
expectedNonce !== null ? ["exp", "iat", "sub", "nonce"] : ["exp", "iat", "sub"],
|
|
355
|
+
},
|
|
356
|
+
(cause) => idTokenError(joseErrorReason(cause)),
|
|
357
|
+
);
|
|
358
|
+
if (Result.isFailure(verified)) return verified;
|
|
359
|
+
if (expectedNonce !== null) {
|
|
360
|
+
const nonce = verified.value.nonce;
|
|
361
|
+
if (typeof nonce !== "string" || !timingSafeEqual(nonce, expectedNonce)) {
|
|
362
|
+
return Result.fail(idTokenError("nonce_mismatch"));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return verified;
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const verifyAccessToken = async (
|
|
369
|
+
token: string,
|
|
370
|
+
audience?: string | readonly string[],
|
|
371
|
+
): ResultAsync<JWTPayload, ServerAuthError> => {
|
|
372
|
+
const accessTokenError = (reason: string): ServerAuthError => ({
|
|
373
|
+
type: "access_token_invalid",
|
|
374
|
+
reason,
|
|
375
|
+
});
|
|
376
|
+
const headerResult = await headerDecoder(() => accessTokenError("malformed_token"))(token);
|
|
377
|
+
if (Result.isFailure(headerResult)) return headerResult;
|
|
378
|
+
const checked = checkHeader(headerResult.value, accessTokenError);
|
|
379
|
+
if (Result.isFailure(checked)) return checked;
|
|
380
|
+
return verifyWithKeySetRetry(
|
|
381
|
+
token,
|
|
382
|
+
{
|
|
383
|
+
// design.md §15.6: access tokens carry typ `at+jwt`.
|
|
384
|
+
typ: "at+jwt",
|
|
385
|
+
requiredClaims: ["exp", "iat", "sub"],
|
|
386
|
+
...(audience !== undefined ? { audience } : {}),
|
|
387
|
+
},
|
|
388
|
+
(cause) => accessTokenError(joseErrorReason(cause)),
|
|
389
|
+
);
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// -------------------------------------------------------------------------
|
|
393
|
+
// Token endpoint
|
|
394
|
+
// -------------------------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
const parseTokenJson = jsonParser(() => ({
|
|
397
|
+
type: "token_response_invalid",
|
|
398
|
+
detail: "invalid_json",
|
|
399
|
+
}));
|
|
400
|
+
|
|
401
|
+
const parseTokenResponse = async (
|
|
402
|
+
res: FetchedText,
|
|
403
|
+
): ResultAsync<TokenResponse, ServerAuthError> => {
|
|
404
|
+
const jsonResult = await parseTokenJson(res.body);
|
|
405
|
+
if (Result.isFailure(jsonResult)) {
|
|
406
|
+
if (res.status === 200) return jsonResult;
|
|
407
|
+
const error: ServerAuthError = {
|
|
408
|
+
type: "token_endpoint_failed",
|
|
409
|
+
status: res.status,
|
|
410
|
+
...retryableIfServerError(res.status),
|
|
411
|
+
};
|
|
412
|
+
return Result.fail(error);
|
|
413
|
+
}
|
|
414
|
+
if (res.status === 200) {
|
|
415
|
+
const parsed = tokenResponseSchema.safeParse(jsonResult.value);
|
|
416
|
+
if (!parsed.success) {
|
|
417
|
+
const error: ServerAuthError = {
|
|
418
|
+
type: "token_response_invalid",
|
|
419
|
+
detail: "schema_validation_failed",
|
|
420
|
+
};
|
|
421
|
+
return Result.fail(error);
|
|
422
|
+
}
|
|
423
|
+
return Result.succeed(parsed.data);
|
|
424
|
+
}
|
|
425
|
+
const parsedError = oauthErrorResponseSchema.safeParse(jsonResult.value);
|
|
426
|
+
if (parsedError.success) {
|
|
427
|
+
const transient =
|
|
428
|
+
parsedError.data.error === "server_error" ||
|
|
429
|
+
parsedError.data.error === "temporarily_unavailable";
|
|
430
|
+
const error: ServerAuthError = {
|
|
431
|
+
type: "token_endpoint_rejected",
|
|
432
|
+
code: parsedError.data.error,
|
|
433
|
+
...(transient ? { retryable: true as const } : {}),
|
|
434
|
+
};
|
|
435
|
+
return Result.fail(error);
|
|
436
|
+
}
|
|
437
|
+
const error: ServerAuthError = {
|
|
438
|
+
type: "token_endpoint_failed",
|
|
439
|
+
status: res.status,
|
|
440
|
+
...retryableIfServerError(res.status),
|
|
441
|
+
};
|
|
442
|
+
return Result.fail(error);
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
const postTokenEndpoint = async (
|
|
446
|
+
params: URLSearchParams,
|
|
447
|
+
): ResultAsync<TokenResponse, ServerAuthError> => {
|
|
448
|
+
const discovery = await getDiscovery();
|
|
449
|
+
return Result.andThen(discovery, async (doc) => {
|
|
450
|
+
const fetched = await fetchBoundedText({
|
|
451
|
+
fetchImpl,
|
|
452
|
+
url: doc.token_endpoint,
|
|
453
|
+
init: {
|
|
454
|
+
method: "POST",
|
|
455
|
+
headers: {
|
|
456
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
457
|
+
authorization: basicAuthorizationHeader(clientId, clientSecret),
|
|
458
|
+
},
|
|
459
|
+
body: params.toString(),
|
|
460
|
+
},
|
|
461
|
+
timeoutMs: TOKEN_ENDPOINT_TIMEOUT_MS,
|
|
462
|
+
maxBytes: TOKEN_RESPONSE_MAX_BYTES,
|
|
463
|
+
});
|
|
464
|
+
return Result.andThen(fetched, parseTokenResponse);
|
|
465
|
+
});
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
const exchangeCode = (input: {
|
|
469
|
+
code: string;
|
|
470
|
+
redirectUri: string;
|
|
471
|
+
codeVerifier: string;
|
|
472
|
+
}): ResultAsync<TokenResponse, ServerAuthError> => {
|
|
473
|
+
const params = new URLSearchParams();
|
|
474
|
+
params.set("grant_type", "authorization_code");
|
|
475
|
+
params.set("code", input.code);
|
|
476
|
+
params.set("redirect_uri", input.redirectUri);
|
|
477
|
+
params.set("code_verifier", input.codeVerifier);
|
|
478
|
+
return postTokenEndpoint(params);
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
const refreshTokens = (refreshToken: string): ResultAsync<TokenResponse, ServerAuthError> => {
|
|
482
|
+
const params = new URLSearchParams();
|
|
483
|
+
params.set("grant_type", "refresh_token");
|
|
484
|
+
params.set("refresh_token", refreshToken);
|
|
485
|
+
return postTokenEndpoint(params);
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
const revokeRefreshToken = async (refreshToken: string): ResultAsync<void, ServerAuthError> => {
|
|
489
|
+
const discovery = await getDiscovery();
|
|
490
|
+
return Result.andThen(discovery, async (doc) => {
|
|
491
|
+
const params = new URLSearchParams();
|
|
492
|
+
params.set("token", refreshToken);
|
|
493
|
+
params.set("token_type_hint", "refresh_token");
|
|
494
|
+
const fetched = await fetchBoundedText({
|
|
495
|
+
fetchImpl,
|
|
496
|
+
url: doc.revocation_endpoint,
|
|
497
|
+
init: {
|
|
498
|
+
method: "POST",
|
|
499
|
+
headers: {
|
|
500
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
501
|
+
authorization: basicAuthorizationHeader(clientId, clientSecret),
|
|
502
|
+
},
|
|
503
|
+
body: params.toString(),
|
|
504
|
+
},
|
|
505
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
506
|
+
maxBytes: REVOCATION_RESPONSE_MAX_BYTES,
|
|
507
|
+
});
|
|
508
|
+
// design.md §15.8: the endpoint returns 200 even for tokens that never
|
|
509
|
+
// existed, so any 2xx is success; the caller (logout) treats the rest
|
|
510
|
+
// as best-effort.
|
|
511
|
+
return Result.andThen(fetched, (res) => {
|
|
512
|
+
if (res.status >= 200 && res.status < 300) return Result.succeed(undefined);
|
|
513
|
+
const error: ServerAuthError = {
|
|
514
|
+
type: "revocation_failed",
|
|
515
|
+
status: res.status,
|
|
516
|
+
...retryableIfServerError(res.status),
|
|
517
|
+
};
|
|
518
|
+
return Result.fail(error);
|
|
519
|
+
});
|
|
520
|
+
});
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
// -------------------------------------------------------------------------
|
|
524
|
+
// Authorize redirect
|
|
525
|
+
// -------------------------------------------------------------------------
|
|
526
|
+
|
|
527
|
+
const buildAuthorizeUrl = (input: AuthorizeUrlInput): ResultAsync<string, ServerAuthError> =>
|
|
528
|
+
Result.mapAsync(getDiscovery(), (doc) => {
|
|
529
|
+
// `authorization_endpoint` is a schema-validated https URL, so `new URL`
|
|
530
|
+
// cannot throw here.
|
|
531
|
+
const url = new URL(doc.authorization_endpoint);
|
|
532
|
+
url.searchParams.set("response_type", "code");
|
|
533
|
+
url.searchParams.set("client_id", clientId);
|
|
534
|
+
url.searchParams.set("redirect_uri", input.redirectUri);
|
|
535
|
+
url.searchParams.set("scope", input.scope);
|
|
536
|
+
url.searchParams.set("state", input.state);
|
|
537
|
+
url.searchParams.set("nonce", input.nonce);
|
|
538
|
+
url.searchParams.set("code_challenge", input.codeChallenge);
|
|
539
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
540
|
+
return url.toString();
|
|
541
|
+
});
|
|
542
|
+
|
|
543
|
+
return {
|
|
544
|
+
buildAuthorizeUrl,
|
|
545
|
+
exchangeCode,
|
|
546
|
+
refreshTokens,
|
|
547
|
+
revokeRefreshToken,
|
|
548
|
+
verifyIdToken,
|
|
549
|
+
verifyAccessToken,
|
|
550
|
+
};
|
|
551
|
+
};
|
package/src/result.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
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
|
+
|
|
15
|
+
export type Success<T> = { readonly type: "Success"; readonly value: T };
|
|
16
|
+
export type Failure<E> = { readonly type: "Failure"; readonly error: E };
|
|
17
|
+
export type Result<T, E> = Success<T> | Failure<E>;
|
|
18
|
+
export type ResultAsync<T, E> = Promise<Result<T, E>>;
|
|
19
|
+
export type ResultMaybeAsync<T, E> = Result<T, E> | ResultAsync<T, E>;
|
|
20
|
+
|
|
21
|
+
const succeed = <T>(value: T): Success<T> => ({ type: "Success", value });
|
|
22
|
+
|
|
23
|
+
const fail = <E>(error: E): Failure<E> => ({ type: "Failure", error });
|
|
24
|
+
|
|
25
|
+
const isSuccess = <T, E>(result: Result<T, E>): result is Success<T> => result.type === "Success";
|
|
26
|
+
|
|
27
|
+
const isFailure = <T, E>(result: Result<T, E>): result is Failure<E> => result.type === "Failure";
|
|
28
|
+
|
|
29
|
+
const map = <T, U, E>(result: Result<T, E>, f: (value: T) => U): Result<U, E> =>
|
|
30
|
+
isSuccess(result) ? succeed(f(result.value)) : result;
|
|
31
|
+
|
|
32
|
+
const mapAsync = async <T, U, E>(
|
|
33
|
+
result: ResultMaybeAsync<T, E>,
|
|
34
|
+
f: (value: T) => U | Promise<U>,
|
|
35
|
+
): ResultAsync<U, E> => {
|
|
36
|
+
const resolved = await result;
|
|
37
|
+
return isSuccess(resolved) ? succeed(await f(resolved.value)) : resolved;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const mapError = <T, E, F>(result: Result<T, E>, f: (error: E) => F): Result<T, F> =>
|
|
41
|
+
isFailure(result) ? fail(f(result.error)) : result;
|
|
42
|
+
|
|
43
|
+
const andThen = async <T, U, E>(
|
|
44
|
+
result: ResultMaybeAsync<T, E>,
|
|
45
|
+
f: (value: T) => ResultMaybeAsync<U, E>,
|
|
46
|
+
): ResultAsync<U, E> => {
|
|
47
|
+
const resolved = await result;
|
|
48
|
+
return isSuccess(resolved) ? f(resolved.value) : resolved;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const orElse = async <T, E, F>(
|
|
52
|
+
result: ResultMaybeAsync<T, E>,
|
|
53
|
+
f: (error: E) => ResultMaybeAsync<T, F>,
|
|
54
|
+
): ResultAsync<T, F> => {
|
|
55
|
+
const resolved = await result;
|
|
56
|
+
return isFailure(resolved) ? f(resolved.error) : resolved;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Wraps a throwing/rejecting boundary exactly once (design.md §5.2). `try`
|
|
61
|
+
* must be an async function; a synchronous throw inside it becomes a promise
|
|
62
|
+
* rejection and is converted by the same `catch` mapper, so callers never see
|
|
63
|
+
* an exception cross the boundary. The `catch` mapper receives `unknown` and
|
|
64
|
+
* must produce a typed error without unvalidated casts.
|
|
65
|
+
*/
|
|
66
|
+
const fn = <A extends readonly unknown[], T, E>(options: {
|
|
67
|
+
readonly try: (...args: A) => Promise<T>;
|
|
68
|
+
readonly catch: (cause: unknown) => E;
|
|
69
|
+
}): ((...args: A) => ResultAsync<T, E>) => {
|
|
70
|
+
return (...args: A) =>
|
|
71
|
+
Promise.resolve()
|
|
72
|
+
.then(() => options.try(...args))
|
|
73
|
+
.then(
|
|
74
|
+
(value): Result<T, E> => succeed(value),
|
|
75
|
+
(cause: unknown): Result<T, E> => fail(options.catch(cause)),
|
|
76
|
+
);
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export const Result = {
|
|
80
|
+
succeed,
|
|
81
|
+
fail,
|
|
82
|
+
isSuccess,
|
|
83
|
+
isFailure,
|
|
84
|
+
map,
|
|
85
|
+
mapAsync,
|
|
86
|
+
mapError,
|
|
87
|
+
andThen,
|
|
88
|
+
orElse,
|
|
89
|
+
fn,
|
|
90
|
+
} as const;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { Result } from "./result.js";
|
|
3
|
+
import { createSealer } from "./sealing.js";
|
|
4
|
+
|
|
5
|
+
const SECRET = "0123456789abcdef0123456789abcdef";
|
|
6
|
+
|
|
7
|
+
describe("createSealer", () => {
|
|
8
|
+
test("seal/unseal round-trips arbitrary JSON payloads", async () => {
|
|
9
|
+
const sealer = createSealer(SECRET);
|
|
10
|
+
const payload = { v: 1, sub: "usr_x", nested: { list: [1, 2, 3] } };
|
|
11
|
+
const sealed = await sealer.seal(payload);
|
|
12
|
+
expect(Result.isSuccess(sealed)).toBe(true);
|
|
13
|
+
if (Result.isFailure(sealed)) return;
|
|
14
|
+
expect(sealed.value).toMatch(/^v1\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/);
|
|
15
|
+
|
|
16
|
+
const unsealed = await sealer.unseal(sealed.value);
|
|
17
|
+
expect(Result.isSuccess(unsealed)).toBe(true);
|
|
18
|
+
if (Result.isSuccess(unsealed)) {
|
|
19
|
+
expect(unsealed.value).toEqual(payload);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("a tampered ciphertext fails closed (GCM auth tag)", async () => {
|
|
24
|
+
const sealer = createSealer(SECRET);
|
|
25
|
+
const sealed = await sealer.seal({ sub: "usr_x" });
|
|
26
|
+
if (Result.isFailure(sealed)) throw new Error("seal failed");
|
|
27
|
+
const parts = sealed.value.split(".");
|
|
28
|
+
const ciphertext = parts[2] ?? "";
|
|
29
|
+
const midpoint = Math.floor(ciphertext.length / 2);
|
|
30
|
+
const replacement = ciphertext[midpoint] === "A" ? "B" : "A";
|
|
31
|
+
const tampered = `${parts[0]}.${parts[1]}.${ciphertext.slice(0, midpoint)}${replacement}${ciphertext.slice(midpoint + 1)}`;
|
|
32
|
+
|
|
33
|
+
const result = await sealer.unseal(tampered);
|
|
34
|
+
expect(Result.isFailure(result)).toBe(true);
|
|
35
|
+
if (Result.isFailure(result)) {
|
|
36
|
+
expect(result.error.type).toBe("seal_verification_failed");
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("a value sealed with a different secret fails closed", async () => {
|
|
41
|
+
const sealed = await createSealer("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").seal({ a: 1 });
|
|
42
|
+
if (Result.isFailure(sealed)) throw new Error("seal failed");
|
|
43
|
+
const result = await createSealer(SECRET).unseal(sealed.value);
|
|
44
|
+
expect(Result.isFailure(result)).toBe(true);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("malformed values are rejected without throwing", async () => {
|
|
48
|
+
const sealer = createSealer(SECRET);
|
|
49
|
+
for (const value of ["", "garbage", "v1.onlytwo", "v2.aaaa.bbbb", "v1.!!!.bbbb"]) {
|
|
50
|
+
const result = await sealer.unseal(value);
|
|
51
|
+
expect(Result.isFailure(result)).toBe(true);
|
|
52
|
+
if (Result.isFailure(result)) {
|
|
53
|
+
expect(result.error.type).toBe("seal_verification_failed");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
});
|