@geektr.cloud/acrux-auth 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +796 -2
- package/package.json +59 -3
- package/src/components/AuthError.vue +45 -0
- package/src/components/AuthLogin.vue +201 -0
- package/src/components/PubKeyClient.vue +477 -0
- package/src/index.ts +82 -0
- package/src/next.ts +22 -0
- package/src/passkey-client.ts +159 -0
- package/src/passkey-metadata.ts +56 -0
- package/src/pubkey-client.ts +183 -0
- package/src/pubkey-proof.ts +179 -0
- package/src/pubkey-transport.ts +107 -0
- package/src/pubkey-types.ts +41 -0
- package/src/server/http.ts +27 -0
- package/src/server/identity.ts +22 -0
- package/src/server/index.ts +10 -0
- package/src/server/passkey/challenge.ts +70 -0
- package/src/server/passkey/config.ts +97 -0
- package/src/server/passkey/index.ts +10 -0
- package/src/server/passkey/routes.ts +310 -0
- package/src/server/passkey/store.ts +84 -0
- package/src/server/provider.ts +90 -0
- package/src/server/providers/cloudflare.ts +83 -0
- package/src/server/providers/custom.ts +47 -0
- package/src/server/providers/github.ts +112 -0
- package/src/server/providers/google.ts +45 -0
- package/src/server/providers/index.ts +4 -0
- package/src/server/pubkey/errors.ts +32 -0
- package/src/server/pubkey/fixtures.ts +156 -0
- package/src/server/pubkey/http.ts +91 -0
- package/src/server/pubkey/index.ts +10 -0
- package/src/server/pubkey/keys.ts +166 -0
- package/src/server/pubkey/resolve.ts +189 -0
- package/src/server/pubkey/resolver.ts +111 -0
- package/src/server/pubkey/verify.ts +119 -0
- package/src/server/pubkey/wkd.ts +78 -0
- package/src/server/pubkey-passkey/index.ts +14 -0
- package/src/server/pubkey-passkey/routes.ts +260 -0
- package/src/server/routes.ts +340 -0
- package/src/server/session.ts +86 -0
- package/src/server/userpass.ts +104 -0
- package/src/types.ts +82 -0
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { Hono, type Context } from "hono";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { passkeyRegistrationMetadataSchema, type PasskeyRegistrationMetadata } from "../../passkey-metadata";
|
|
4
|
+
import {
|
|
5
|
+
parsePubKeyCredentialProofMessage,
|
|
6
|
+
parsePubKeyProofMessage,
|
|
7
|
+
PUBKEY_PROOF_CREDENTIAL_ID_MAX_LENGTH,
|
|
8
|
+
PUBKEY_PROOF_CREDENTIAL_PUBLIC_KEY_MAX_LENGTH,
|
|
9
|
+
PUBKEY_PROOF_MESSAGE_MAX_LENGTH,
|
|
10
|
+
PubKeyProofError,
|
|
11
|
+
type ParsedPubKeyCredentialProofMessage,
|
|
12
|
+
type ParsedPubKeyProofMessage,
|
|
13
|
+
type PubKeyProofMode,
|
|
14
|
+
} from "../../pubkey-proof";
|
|
15
|
+
import type {
|
|
16
|
+
PubKeyPasskeyCredential,
|
|
17
|
+
PubKeyPasskeyKeysResponse,
|
|
18
|
+
PubKeyPasskeyRegisterRequest,
|
|
19
|
+
PubKeyPasskeyRegisterResponse,
|
|
20
|
+
} from "../../pubkey-types";
|
|
21
|
+
import { hasJsonContentType, hasSameOrigin, parsePublicOrigin } from "../http";
|
|
22
|
+
import { parsePasskeyCredential, type PasskeyCredentialConfig } from "../passkey/config";
|
|
23
|
+
import { PasskeyCredentialConflictError, type PasskeyCredentialStore } from "../passkey/store";
|
|
24
|
+
import { PubKeyError } from "../pubkey/errors";
|
|
25
|
+
import type { PubKeyResolver } from "../pubkey/resolver";
|
|
26
|
+
import { verifyDetachedSignature } from "../pubkey/verify";
|
|
27
|
+
|
|
28
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
29
|
+
const MAX_FINGERPRINT_LENGTH = 128;
|
|
30
|
+
const MAX_SIGNATURE_LENGTH = 16_384;
|
|
31
|
+
|
|
32
|
+
const credentialSchema = z.strictObject({
|
|
33
|
+
id: z.string().min(1).max(PUBKEY_PROOF_CREDENTIAL_ID_MAX_LENGTH),
|
|
34
|
+
public_key: z.string().min(1).max(PUBKEY_PROOF_CREDENTIAL_PUBLIC_KEY_MAX_LENGTH),
|
|
35
|
+
}) satisfies z.ZodType<PubKeyPasskeyCredential>;
|
|
36
|
+
|
|
37
|
+
const registerSchema = z.strictObject({
|
|
38
|
+
fingerprint: z.string().min(1).max(MAX_FINGERPRINT_LENGTH),
|
|
39
|
+
message: z.string().min(1).max(PUBKEY_PROOF_MESSAGE_MAX_LENGTH),
|
|
40
|
+
signature: z.string().min(1).max(MAX_SIGNATURE_LENGTH),
|
|
41
|
+
credential: credentialSchema,
|
|
42
|
+
metadata: passkeyRegistrationMetadataSchema.optional(),
|
|
43
|
+
}) satisfies z.ZodType<PubKeyPasskeyRegisterRequest>;
|
|
44
|
+
|
|
45
|
+
export type {
|
|
46
|
+
PubKeyPasskeyCredential,
|
|
47
|
+
PubKeyPasskeyKeysResponse,
|
|
48
|
+
PubKeyPasskeyRefreshResponse,
|
|
49
|
+
PubKeyPasskeyRegisterRequest,
|
|
50
|
+
PubKeyPasskeyRegisterResponse,
|
|
51
|
+
} from "../../pubkey-types";
|
|
52
|
+
|
|
53
|
+
export interface PubKeyPasskeyErrorResponse {
|
|
54
|
+
error: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type PubKeyPasskeyCompletionResult = "registered" | "conflict" | "forbidden";
|
|
58
|
+
|
|
59
|
+
export interface PubKeyPasskeyCompletionInput {
|
|
60
|
+
/** 已从请求的 public_key 转换一次的宿主凭据格式。 */
|
|
61
|
+
credential: PasskeyCredentialConfig;
|
|
62
|
+
/** 通过严格边界校验的可选登记元数据;未提供时保持缺省。 */
|
|
63
|
+
metadata?: PasskeyRegistrationMetadata;
|
|
64
|
+
/** 与当前 proofMode 对应、已完成 credential 绑定与时间窗校验的 proof。 */
|
|
65
|
+
proof: ParsedPubKeyProofMessage | ParsedPubKeyCredentialProofMessage;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export type PubKeyPasskeyCompleteRegistration = (
|
|
69
|
+
input: PubKeyPasskeyCompletionInput,
|
|
70
|
+
) => Promise<PubKeyPasskeyCompletionResult>;
|
|
71
|
+
|
|
72
|
+
export type PubKeyPasskeyRoutesOptions = {
|
|
73
|
+
/** per-isolate 公钥解析与缓存控制器。 */
|
|
74
|
+
resolver: PubKeyResolver;
|
|
75
|
+
/** 反向代理后的公开 origin;未配置时使用请求 origin。 */
|
|
76
|
+
publicOrigin?: string;
|
|
77
|
+
/**
|
|
78
|
+
* proof message 模式;默认 `username` legacy 格式。
|
|
79
|
+
* 显式配置 `credential-only` 后只接受 `${uuidv7}:${id}:${public_key}`。
|
|
80
|
+
*/
|
|
81
|
+
proofMode?: PubKeyProofMode;
|
|
82
|
+
} & (
|
|
83
|
+
| {
|
|
84
|
+
/** 注册成功后的内存 Passkey 凭据集合。 */
|
|
85
|
+
store: PasskeyCredentialStore;
|
|
86
|
+
completeRegistration?: never;
|
|
87
|
+
}
|
|
88
|
+
| {
|
|
89
|
+
store?: never;
|
|
90
|
+
/** 验签与凭据校验通过后,由宿主完成持久化或登记门禁。 */
|
|
91
|
+
completeRegistration: PubKeyPasskeyCompleteRegistration;
|
|
92
|
+
}
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
type ErrorStatus = 400 | 401 | 403 | 409 | 410 | 413 | 415 | 500 | 502 | 503;
|
|
96
|
+
|
|
97
|
+
const errorResponse = (c: Context, status: ErrorStatus, error: string) =>
|
|
98
|
+
c.json({ error } satisfies PubKeyPasskeyErrorResponse, status);
|
|
99
|
+
|
|
100
|
+
type ParsedRegisterBody = { ok: true; value: PubKeyPasskeyRegisterRequest } | { ok: false; status: 400 | 413 };
|
|
101
|
+
|
|
102
|
+
const parseRegisterBody = async (c: Context): Promise<ParsedRegisterBody> => {
|
|
103
|
+
const contentLength = c.req.header("content-length");
|
|
104
|
+
if (contentLength) {
|
|
105
|
+
const length = Number(contentLength);
|
|
106
|
+
if (Number.isFinite(length) && length > MAX_BODY_BYTES) return { ok: false, status: 413 };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let raw: string;
|
|
110
|
+
try {
|
|
111
|
+
raw = await c.req.text();
|
|
112
|
+
} catch {
|
|
113
|
+
return { ok: false, status: 400 };
|
|
114
|
+
}
|
|
115
|
+
if (raw.length > MAX_BODY_BYTES) return { ok: false, status: 413 };
|
|
116
|
+
|
|
117
|
+
let json: unknown;
|
|
118
|
+
try {
|
|
119
|
+
json = JSON.parse(raw);
|
|
120
|
+
} catch {
|
|
121
|
+
return { ok: false, status: 400 };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const parsed = registerSchema.safeParse(json);
|
|
125
|
+
return parsed.success ? { ok: true, value: parsed.data } : { ok: false, status: 400 };
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* OpenPGP 授权 Passkey 注册路由:`GET /keys`、`POST /refresh`、`POST /register`。
|
|
130
|
+
*
|
|
131
|
+
* - `GET /keys` 与 `POST /refresh` 公开;refresh 只要求同源,匿名调用是有意接受的风险。
|
|
132
|
+
* - `POST /register` 只做 detached signature 验签,不保存 pending、不写 session、
|
|
133
|
+
* 不保存 username。成功后加入内存 store,或等待宿主的 completeRegistration。
|
|
134
|
+
*/
|
|
135
|
+
export const createPubKeyPasskeyRoutes = (options: PubKeyPasskeyRoutesOptions) => {
|
|
136
|
+
const { resolver, store, completeRegistration } = options;
|
|
137
|
+
if (Boolean(store) === Boolean(completeRegistration)) {
|
|
138
|
+
throw new Error("createPubKeyPasskeyRoutes: provide exactly one of store or completeRegistration");
|
|
139
|
+
}
|
|
140
|
+
const publicOrigin = parsePublicOrigin(options.publicOrigin);
|
|
141
|
+
const proofMode = options.proofMode ?? "username";
|
|
142
|
+
if (proofMode !== "username" && proofMode !== "credential-only") {
|
|
143
|
+
throw new Error("createPubKeyPasskeyRoutes: proofMode must be 'username' or 'credential-only'");
|
|
144
|
+
}
|
|
145
|
+
const parseProof = proofMode === "credential-only" ? parsePubKeyCredentialProofMessage : parsePubKeyProofMessage;
|
|
146
|
+
|
|
147
|
+
return new Hono()
|
|
148
|
+
.get("/keys", (c) =>
|
|
149
|
+
c.json({
|
|
150
|
+
status: resolver.status,
|
|
151
|
+
keys: resolver.list(),
|
|
152
|
+
} satisfies PubKeyPasskeyKeysResponse),
|
|
153
|
+
)
|
|
154
|
+
.post("/refresh", async (c) => {
|
|
155
|
+
if (!hasSameOrigin(c, publicOrigin)) return errorResponse(c, 403, "Forbidden");
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
await resolver.refresh();
|
|
159
|
+
} catch {
|
|
160
|
+
// 失败时 resolver 保留旧缓存;这里只回通用错误,不暴露内部异常。
|
|
161
|
+
return errorResponse(c, 502, "Key refresh failed");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return c.json({
|
|
165
|
+
status: resolver.status,
|
|
166
|
+
keys: resolver.list(),
|
|
167
|
+
} satisfies PubKeyPasskeyKeysResponse);
|
|
168
|
+
})
|
|
169
|
+
.post("/register", async (c) => {
|
|
170
|
+
if (!hasSameOrigin(c, publicOrigin)) return errorResponse(c, 403, "Forbidden");
|
|
171
|
+
if (!hasJsonContentType(c)) return errorResponse(c, 415, "Unsupported Media Type");
|
|
172
|
+
|
|
173
|
+
const parsed = await parseRegisterBody(c);
|
|
174
|
+
if (!parsed.ok) {
|
|
175
|
+
return parsed.status === 413
|
|
176
|
+
? errorResponse(c, 413, "Payload Too Large")
|
|
177
|
+
: errorResponse(c, 400, "Bad Request");
|
|
178
|
+
}
|
|
179
|
+
const body = parsed.value;
|
|
180
|
+
|
|
181
|
+
const keys = resolver.list();
|
|
182
|
+
// refresh 期间 status 为 loading、失败后为 error,但只要还有旧缓存就继续服务。
|
|
183
|
+
if (keys.length === 0) return errorResponse(c, 503, "Service Unavailable");
|
|
184
|
+
|
|
185
|
+
let proof: PubKeyPasskeyCompletionInput["proof"];
|
|
186
|
+
try {
|
|
187
|
+
proof = parseProof(body.message, body.credential);
|
|
188
|
+
} catch (cause) {
|
|
189
|
+
if (cause instanceof PubKeyProofError) {
|
|
190
|
+
if (cause.code === "outside-time-window") return errorResponse(c, 410, "Gone");
|
|
191
|
+
if (cause.code === "credential-mismatch") return errorResponse(c, 401, "Unauthorized");
|
|
192
|
+
return errorResponse(c, 400, "Bad Request");
|
|
193
|
+
}
|
|
194
|
+
return errorResponse(c, 500, "Internal Server Error");
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let verified: boolean;
|
|
198
|
+
try {
|
|
199
|
+
verified = await verifyDetachedSignature({
|
|
200
|
+
keys,
|
|
201
|
+
fingerprint: body.fingerprint,
|
|
202
|
+
message: body.message,
|
|
203
|
+
signature: body.signature,
|
|
204
|
+
});
|
|
205
|
+
} catch (cause) {
|
|
206
|
+
// fingerprint / signature 的 OpenPGP 解析失败属于客户端输入错误,不能变成 500。
|
|
207
|
+
if (cause instanceof PubKeyError) return errorResponse(c, 400, "Bad Request");
|
|
208
|
+
return errorResponse(c, 500, "Internal Server Error");
|
|
209
|
+
}
|
|
210
|
+
if (!verified) return errorResponse(c, 401, "Unauthorized");
|
|
211
|
+
|
|
212
|
+
const credential = {
|
|
213
|
+
id: body.credential.id,
|
|
214
|
+
publicKey: body.credential.public_key,
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
if (completeRegistration) {
|
|
218
|
+
try {
|
|
219
|
+
// completion 分支没有 store.add 代为校验,成功前必须完成相同边界检查。
|
|
220
|
+
parsePasskeyCredential(credential);
|
|
221
|
+
} catch {
|
|
222
|
+
return errorResponse(c, 400, "Bad Request");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
let result: PubKeyPasskeyCompletionResult;
|
|
226
|
+
try {
|
|
227
|
+
result = await completeRegistration({
|
|
228
|
+
credential,
|
|
229
|
+
proof,
|
|
230
|
+
...(body.metadata === undefined ? {} : { metadata: body.metadata }),
|
|
231
|
+
});
|
|
232
|
+
} catch {
|
|
233
|
+
return errorResponse(c, 500, "Internal Server Error");
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (result === "registered") {
|
|
237
|
+
return c.json({ registered: true, id: credential.id } satisfies PubKeyPasskeyRegisterResponse);
|
|
238
|
+
}
|
|
239
|
+
if (result === "conflict") return errorResponse(c, 409, "Conflict");
|
|
240
|
+
if (result === "forbidden") return errorResponse(c, 403, "Forbidden");
|
|
241
|
+
return errorResponse(c, 500, "Internal Server Error");
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (store) {
|
|
245
|
+
try {
|
|
246
|
+
const registered = store.add(credential);
|
|
247
|
+
return c.json({ registered: true, id: registered.id } satisfies PubKeyPasskeyRegisterResponse);
|
|
248
|
+
} catch (cause) {
|
|
249
|
+
if (cause instanceof PasskeyCredentialConflictError) return errorResponse(c, 409, "Conflict");
|
|
250
|
+
// 默认 store 的非冲突异常继续保持原有 400 语义。
|
|
251
|
+
return errorResponse(c, 400, "Bad Request");
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// 启动时的互斥检查保证不会到达这里。
|
|
256
|
+
return errorResponse(c, 500, "Internal Server Error");
|
|
257
|
+
});
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
export type PubKeyPasskeyRoutes = ReturnType<typeof createPubKeyPasskeyRoutes>;
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { Hono, type Context } from "hono";
|
|
2
|
+
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
|
3
|
+
import * as client from "openid-client";
|
|
4
|
+
import { sanitizeNext } from "../next";
|
|
5
|
+
import type { AuthIdentity, AuthProviderPublic } from "./identity";
|
|
6
|
+
import { publicProvider } from "./identity";
|
|
7
|
+
import type { AuthProviderDefinition } from "./provider";
|
|
8
|
+
|
|
9
|
+
const DEFAULT_TRANSACTION_COOKIE = "__Host-acrux_oidc_tx";
|
|
10
|
+
const TRANSACTION_VALUE_PREFIX = "tx1.";
|
|
11
|
+
const TRANSACTION_MAX_AGE_SECONDS = 600;
|
|
12
|
+
const TRANSACTION_MAX_AGE_MS = TRANSACTION_MAX_AGE_SECONDS * 1000;
|
|
13
|
+
const TRANSACTION_CLOCK_SKEW_MS = 60_000;
|
|
14
|
+
const MAX_PROVIDER_ERROR_CHARACTERS = 128;
|
|
15
|
+
const MAX_PROVIDER_DESCRIPTION_CHARACTERS = 512;
|
|
16
|
+
|
|
17
|
+
const stripControlCharacters = (value: string): string => {
|
|
18
|
+
let result = "";
|
|
19
|
+
for (const character of value) {
|
|
20
|
+
const code = character.charCodeAt(0);
|
|
21
|
+
if (code > 0x1f && code !== 0x7f) result += character;
|
|
22
|
+
}
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const sanitizeProviderText = (value: string | undefined, maxCharacters: number): string | undefined => {
|
|
27
|
+
if (!value) return undefined;
|
|
28
|
+
const cleaned = stripControlCharacters(value).trim();
|
|
29
|
+
if (!cleaned) return undefined;
|
|
30
|
+
const truncated = [...cleaned].slice(0, maxCharacters).join("").trim();
|
|
31
|
+
return truncated || undefined;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const defaultErrorRedirect = (description?: string): string => {
|
|
35
|
+
const params = new URLSearchParams({ error: "oidc_failed" });
|
|
36
|
+
if (description) params.set("error_description", description);
|
|
37
|
+
return `/login?${params.toString()}`;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const transactionCookieOptions = {
|
|
41
|
+
httpOnly: true,
|
|
42
|
+
secure: true,
|
|
43
|
+
sameSite: "Lax",
|
|
44
|
+
path: "/",
|
|
45
|
+
} as const;
|
|
46
|
+
|
|
47
|
+
interface OidcTransaction {
|
|
48
|
+
provider: string;
|
|
49
|
+
state: string;
|
|
50
|
+
codeVerifier: string;
|
|
51
|
+
nonce?: string;
|
|
52
|
+
next: string;
|
|
53
|
+
/** 服务端签发时间(epoch ms),用于 cookie Max-Age 之外的二次有效期校验。 */
|
|
54
|
+
iat: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface OidcSuccessContext {
|
|
58
|
+
c: Context;
|
|
59
|
+
provider: AuthProviderPublic;
|
|
60
|
+
identity: AuthIdentity;
|
|
61
|
+
next: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface OidcErrorContext {
|
|
65
|
+
c: Context;
|
|
66
|
+
provider?: AuthProviderPublic;
|
|
67
|
+
code: "oidc_failed";
|
|
68
|
+
/** 内部异常,仅用于服务端日志;不要拼进 URL。 */
|
|
69
|
+
error: unknown;
|
|
70
|
+
next: string;
|
|
71
|
+
/** 仅来自授权回调 query 的 OAuth error,已去控制字符并截断。 */
|
|
72
|
+
providerError?: string;
|
|
73
|
+
/**
|
|
74
|
+
* 仅来自授权回调 query 的 OAuth error_description,已去控制字符、trim、截断到 512 字符。
|
|
75
|
+
* 这是 IdP 文本,只能按纯文本展示,不能当 HTML。
|
|
76
|
+
*/
|
|
77
|
+
providerErrorDescription?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface OidcRoutesOptions {
|
|
81
|
+
providers: Record<string, AuthProviderDefinition>;
|
|
82
|
+
/** 事务 cookie 的 HMAC 密钥。可用 app session secret,但必须显式传入。 */
|
|
83
|
+
secret: string;
|
|
84
|
+
transactionCookieName?: string;
|
|
85
|
+
/** 生产环境显式配置,例如 `https://acrux.example.com`;未配置时使用当前请求 origin。 */
|
|
86
|
+
publicOrigin?: string;
|
|
87
|
+
/** 路由挂载路径,例如 `/api/auth/oidc`;未配置时从当前 start 路径推导。 */
|
|
88
|
+
mountPath?: string;
|
|
89
|
+
/** 必须由 app 决定 session / allowlist / redirect;返回 Response 时用 `c` 构造。 */
|
|
90
|
+
onSuccess: (context: OidcSuccessContext) => Response | Promise<Response>;
|
|
91
|
+
/**
|
|
92
|
+
* 可选错误处理;默认重定向到 `/login?error=oidc_failed`。
|
|
93
|
+
* 覆盖时必须像 `onSuccess` 一样用 `c` 构造 Response,以保留事务 cookie 清理头。
|
|
94
|
+
*/
|
|
95
|
+
onError?: (context: OidcErrorContext) => Response | Promise<Response>;
|
|
96
|
+
/** 自定义安全错误重定向;必须包含自己的 query。 */
|
|
97
|
+
errorRedirect?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const parseTransaction = (value: string | false | undefined): OidcTransaction | undefined => {
|
|
101
|
+
if (typeof value !== "string" || !value.startsWith(TRANSACTION_VALUE_PREFIX)) return undefined;
|
|
102
|
+
try {
|
|
103
|
+
const parsed: unknown = JSON.parse(value.slice(TRANSACTION_VALUE_PREFIX.length));
|
|
104
|
+
if (!parsed || typeof parsed !== "object") return undefined;
|
|
105
|
+
const record = parsed as Record<string, unknown>;
|
|
106
|
+
if (
|
|
107
|
+
typeof record.provider !== "string" ||
|
|
108
|
+
typeof record.state !== "string" ||
|
|
109
|
+
typeof record.codeVerifier !== "string" ||
|
|
110
|
+
typeof record.iat !== "number" ||
|
|
111
|
+
!Number.isFinite(record.iat)
|
|
112
|
+
) {
|
|
113
|
+
return undefined;
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
provider: record.provider,
|
|
117
|
+
state: record.state,
|
|
118
|
+
codeVerifier: record.codeVerifier,
|
|
119
|
+
nonce: typeof record.nonce === "string" ? record.nonce : undefined,
|
|
120
|
+
next: sanitizeNext(typeof record.next === "string" ? record.next : undefined),
|
|
121
|
+
iat: record.iat,
|
|
122
|
+
};
|
|
123
|
+
} catch {
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* OIDC / OAuth2 路由:
|
|
130
|
+
* `GET /providers`、`GET /:provider/start`、`GET /:provider/callback`。
|
|
131
|
+
*
|
|
132
|
+
* 授权码 + S256 PKCE + state 始终启用;OIDC provider 额外强制 nonce。
|
|
133
|
+
* 事务保存在 signed HttpOnly cookie,provider 绑定,callback 读取后立即删除。
|
|
134
|
+
*/
|
|
135
|
+
export const createOidcRoutes = (options: OidcRoutesOptions) => {
|
|
136
|
+
if (!options.secret) throw new Error("createOidcRoutes: secret is required");
|
|
137
|
+
|
|
138
|
+
const { providers, onSuccess } = options;
|
|
139
|
+
const transactionCookieName = options.transactionCookieName ?? DEFAULT_TRANSACTION_COOKIE;
|
|
140
|
+
const customErrorRedirect = options.errorRedirect;
|
|
141
|
+
const publicOrigin = options.publicOrigin ? new URL(options.publicOrigin).origin : undefined;
|
|
142
|
+
const mountPath = options.mountPath?.replace(/\/+$/, "");
|
|
143
|
+
|
|
144
|
+
for (const provider of Object.values(providers)) {
|
|
145
|
+
if (!provider.redirectUri) continue;
|
|
146
|
+
const redirectUrl = new URL(provider.redirectUri);
|
|
147
|
+
if (redirectUrl.search || redirectUrl.hash) {
|
|
148
|
+
throw new Error(`createOidcRoutes: provider "${provider.id}" redirectUri must not contain query or hash`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const fail = async (context: OidcErrorContext): Promise<Response> => {
|
|
153
|
+
if (options.onError) return options.onError(context);
|
|
154
|
+
// 自定义 errorRedirect 保持原样;默认值才附上授权回调的 description。
|
|
155
|
+
const location = customErrorRedirect ?? defaultErrorRedirect(context.providerErrorDescription);
|
|
156
|
+
return context.c.redirect(location, 302);
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
const resolveRedirectUri = (c: Context, provider: AuthProviderDefinition): string => {
|
|
160
|
+
if (provider.redirectUri) return provider.redirectUri;
|
|
161
|
+
|
|
162
|
+
const requestUrl = new URL(c.req.url);
|
|
163
|
+
const callbackPath = mountPath
|
|
164
|
+
? `${mountPath}/${provider.id}/callback`
|
|
165
|
+
: requestUrl.pathname.replace(/\/start$/, "/callback");
|
|
166
|
+
|
|
167
|
+
return new URL(callbackPath, publicOrigin ?? requestUrl.origin).href;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
return new Hono()
|
|
171
|
+
.get("/providers", (c) => c.json(Object.values(providers).map((provider) => publicProvider(provider))))
|
|
172
|
+
.get("/:provider/start", async (c) => {
|
|
173
|
+
const provider = providers[c.req.param("provider")];
|
|
174
|
+
const next = sanitizeNext(c.req.query("next"));
|
|
175
|
+
if (!provider) {
|
|
176
|
+
return fail({ c, code: "oidc_failed", error: new Error("Unknown auth provider"), next });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
const config = await provider.getConfiguration();
|
|
181
|
+
const redirectUri = resolveRedirectUri(c, provider);
|
|
182
|
+
const state = client.randomState();
|
|
183
|
+
const codeVerifier = client.randomPKCECodeVerifier();
|
|
184
|
+
const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier);
|
|
185
|
+
const nonce = provider.usesOidc ? client.randomNonce() : undefined;
|
|
186
|
+
|
|
187
|
+
const parameters: Record<string, string> = {
|
|
188
|
+
redirect_uri: redirectUri,
|
|
189
|
+
scope: provider.scopes.join(" "),
|
|
190
|
+
state,
|
|
191
|
+
code_challenge: codeChallenge,
|
|
192
|
+
code_challenge_method: "S256",
|
|
193
|
+
};
|
|
194
|
+
if (nonce) parameters.nonce = nonce;
|
|
195
|
+
|
|
196
|
+
const authorizationUrl = client.buildAuthorizationUrl(config, parameters);
|
|
197
|
+
const transaction: OidcTransaction = {
|
|
198
|
+
provider: provider.id,
|
|
199
|
+
state,
|
|
200
|
+
codeVerifier,
|
|
201
|
+
nonce,
|
|
202
|
+
next,
|
|
203
|
+
iat: Date.now(),
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
await setSignedCookie(
|
|
207
|
+
c,
|
|
208
|
+
transactionCookieName,
|
|
209
|
+
`${TRANSACTION_VALUE_PREFIX}${JSON.stringify(transaction)}`,
|
|
210
|
+
options.secret,
|
|
211
|
+
{
|
|
212
|
+
...transactionCookieOptions,
|
|
213
|
+
maxAge: TRANSACTION_MAX_AGE_SECONDS,
|
|
214
|
+
},
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
return c.redirect(authorizationUrl.href, 302);
|
|
218
|
+
} catch (error) {
|
|
219
|
+
return fail({ c, provider: publicProvider(provider), code: "oidc_failed", error, next });
|
|
220
|
+
}
|
|
221
|
+
})
|
|
222
|
+
.get("/:provider/callback", async (c) => {
|
|
223
|
+
const provider = providers[c.req.param("provider")];
|
|
224
|
+
if (!provider) {
|
|
225
|
+
// 未知 provider 的 callback 可能混入其它 provider 的 tx cookie,不能删除它。
|
|
226
|
+
return fail({
|
|
227
|
+
c,
|
|
228
|
+
code: "oidc_failed",
|
|
229
|
+
error: new Error("Unknown auth provider"),
|
|
230
|
+
next: "/",
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
let raw: string | false | undefined;
|
|
235
|
+
try {
|
|
236
|
+
raw = await getSignedCookie(c, options.secret, transactionCookieName);
|
|
237
|
+
} catch {
|
|
238
|
+
raw = undefined;
|
|
239
|
+
}
|
|
240
|
+
// 单次使用:读取后立即删除,无论后续校验是否通过。
|
|
241
|
+
deleteCookie(c, transactionCookieName, transactionCookieOptions);
|
|
242
|
+
|
|
243
|
+
const transaction = parseTransaction(raw);
|
|
244
|
+
if (!transaction || transaction.provider !== provider.id) {
|
|
245
|
+
return fail({
|
|
246
|
+
c,
|
|
247
|
+
provider: publicProvider(provider),
|
|
248
|
+
code: "oidc_failed",
|
|
249
|
+
error: new Error("Missing or mismatched OIDC transaction"),
|
|
250
|
+
next: transaction?.next ?? "/",
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const age = Date.now() - transaction.iat;
|
|
255
|
+
if (age > TRANSACTION_MAX_AGE_MS || age < -TRANSACTION_CLOCK_SKEW_MS) {
|
|
256
|
+
return fail({
|
|
257
|
+
c,
|
|
258
|
+
provider: publicProvider(provider),
|
|
259
|
+
code: "oidc_failed",
|
|
260
|
+
error: new Error("OIDC transaction has expired"),
|
|
261
|
+
next: transaction.next,
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (provider.usesOidc && !transaction.nonce) {
|
|
266
|
+
return fail({
|
|
267
|
+
c,
|
|
268
|
+
provider: publicProvider(provider),
|
|
269
|
+
code: "oidc_failed",
|
|
270
|
+
error: new Error("OIDC transaction is missing nonce"),
|
|
271
|
+
next: transaction.next,
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const rawProviderError = c.req.query("error");
|
|
276
|
+
if (rawProviderError) {
|
|
277
|
+
// 错误回调跳过 token exchange,因此必须在这里自行完成 state 绑定校验。
|
|
278
|
+
if (c.req.query("state") !== transaction.state) {
|
|
279
|
+
return fail({
|
|
280
|
+
c,
|
|
281
|
+
provider: publicProvider(provider),
|
|
282
|
+
code: "oidc_failed",
|
|
283
|
+
error: new Error("Authorization error callback state mismatch"),
|
|
284
|
+
next: transaction.next,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return fail({
|
|
289
|
+
c,
|
|
290
|
+
provider: publicProvider(provider),
|
|
291
|
+
code: "oidc_failed",
|
|
292
|
+
error: new Error("Authorization server returned an error"),
|
|
293
|
+
next: transaction.next,
|
|
294
|
+
providerError: sanitizeProviderText(rawProviderError, MAX_PROVIDER_ERROR_CHARACTERS),
|
|
295
|
+
providerErrorDescription: sanitizeProviderText(
|
|
296
|
+
c.req.query("error_description"),
|
|
297
|
+
MAX_PROVIDER_DESCRIPTION_CHARACTERS,
|
|
298
|
+
),
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
let identity: AuthIdentity;
|
|
303
|
+
try {
|
|
304
|
+
const config = await provider.getConfiguration();
|
|
305
|
+
const checks: client.AuthorizationCodeGrantChecks = {
|
|
306
|
+
pkceCodeVerifier: transaction.codeVerifier,
|
|
307
|
+
expectedState: transaction.state,
|
|
308
|
+
idTokenExpected: provider.usesOidc,
|
|
309
|
+
};
|
|
310
|
+
if (provider.usesOidc) checks.expectedNonce = transaction.nonce;
|
|
311
|
+
|
|
312
|
+
const callbackUrl = new URL(c.req.url);
|
|
313
|
+
const exchangeUrl = new URL(resolveRedirectUri(c, provider));
|
|
314
|
+
exchangeUrl.search = callbackUrl.search;
|
|
315
|
+
exchangeUrl.hash = "";
|
|
316
|
+
|
|
317
|
+
const tokens = await client.authorizationCodeGrant(config, exchangeUrl, checks);
|
|
318
|
+
const accessToken = tokens.access_token;
|
|
319
|
+
if (!accessToken) throw new Error("Authorization server did not return an access token");
|
|
320
|
+
|
|
321
|
+
identity = await provider.resolveIdentity({
|
|
322
|
+
config,
|
|
323
|
+
tokens,
|
|
324
|
+
claims: tokens.claims(),
|
|
325
|
+
accessToken,
|
|
326
|
+
});
|
|
327
|
+
} catch (error) {
|
|
328
|
+
return fail({ c, provider: publicProvider(provider), code: "oidc_failed", error, next: transaction.next });
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return onSuccess({
|
|
332
|
+
c,
|
|
333
|
+
provider: publicProvider(provider),
|
|
334
|
+
identity,
|
|
335
|
+
next: transaction.next,
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
export type OidcRoutes = ReturnType<typeof createOidcRoutes>;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { Context } from "hono";
|
|
2
|
+
import { deleteCookie, getSignedCookie, setSignedCookie } from "hono/cookie";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_COOKIE_NAME = "__Host-acrux_session";
|
|
5
|
+
const DEFAULT_MAX_AGE = 60 * 60 * 24 * 7;
|
|
6
|
+
const SESSION_VALUE_PREFIX = "s2.";
|
|
7
|
+
|
|
8
|
+
export interface AuthSessionOptions {
|
|
9
|
+
/** HMAC 签名密钥。显式注入,不读取 cloudflare:workers。 */
|
|
10
|
+
secret: string;
|
|
11
|
+
/** 默认 `__Host-acrux_session`(要求 Secure + Path=/ + 无 Domain)。 */
|
|
12
|
+
cookieName?: string;
|
|
13
|
+
/** 秒;默认 7 天。 */
|
|
14
|
+
maxAge?: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 基于 Hono signed cookie 的会话。
|
|
19
|
+
*
|
|
20
|
+
* cookie 值保存应用传入的 opaque identity(例如 username 或 session id)及签发/过期时间,
|
|
21
|
+
* 不保存 access token / refresh token / ID token。
|
|
22
|
+
*/
|
|
23
|
+
export interface AuthSession {
|
|
24
|
+
readonly cookieName: string;
|
|
25
|
+
set(c: Context, identity: string): Promise<void>;
|
|
26
|
+
get(c: Context): Promise<string | undefined>;
|
|
27
|
+
clear(c: Context): void;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const parseTimestamp = (value: string): number | undefined => {
|
|
31
|
+
if (!/^\d+$/.test(value)) return undefined;
|
|
32
|
+
const timestamp = Number(value);
|
|
33
|
+
return Number.isSafeInteger(timestamp) ? timestamp : undefined;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const parseSessionIdentity = (value: string): string | undefined => {
|
|
37
|
+
if (!value.startsWith(SESSION_VALUE_PREFIX)) return undefined;
|
|
38
|
+
const iatEnd = value.indexOf(".", SESSION_VALUE_PREFIX.length);
|
|
39
|
+
if (iatEnd < 0) return undefined;
|
|
40
|
+
const expEnd = value.indexOf(".", iatEnd + 1);
|
|
41
|
+
if (expEnd < 0) return undefined;
|
|
42
|
+
|
|
43
|
+
const iat = parseTimestamp(value.slice(SESSION_VALUE_PREFIX.length, iatEnd));
|
|
44
|
+
const exp = parseTimestamp(value.slice(iatEnd + 1, expEnd));
|
|
45
|
+
const identity = value.slice(expEnd + 1);
|
|
46
|
+
if (iat === undefined || exp === undefined || exp <= iat || !identity) return undefined;
|
|
47
|
+
if (Math.floor(Date.now() / 1000) >= exp) return undefined;
|
|
48
|
+
return identity;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export const createAuthSession = (options: AuthSessionOptions): AuthSession => {
|
|
52
|
+
const { secret, cookieName = DEFAULT_COOKIE_NAME, maxAge = DEFAULT_MAX_AGE } = options;
|
|
53
|
+
if (!secret) throw new Error("createAuthSession: secret is required");
|
|
54
|
+
|
|
55
|
+
const cookieOptions = {
|
|
56
|
+
httpOnly: true,
|
|
57
|
+
secure: true,
|
|
58
|
+
sameSite: "Lax",
|
|
59
|
+
path: "/",
|
|
60
|
+
} as const;
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
cookieName,
|
|
64
|
+
async set(c, identity) {
|
|
65
|
+
if (!identity) throw new Error("createAuthSession: identity must not be empty");
|
|
66
|
+
const iat = Math.floor(Date.now() / 1000);
|
|
67
|
+
const exp = iat + maxAge;
|
|
68
|
+
await setSignedCookie(c, cookieName, `${SESSION_VALUE_PREFIX}${iat}.${exp}.${identity}`, secret, {
|
|
69
|
+
...cookieOptions,
|
|
70
|
+
maxAge,
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
async get(c) {
|
|
74
|
+
let value: string | false | undefined;
|
|
75
|
+
try {
|
|
76
|
+
value = await getSignedCookie(c, secret, cookieName);
|
|
77
|
+
} catch {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
return typeof value === "string" ? parseSessionIdentity(value) : undefined;
|
|
81
|
+
},
|
|
82
|
+
clear(c) {
|
|
83
|
+
deleteCookie(c, cookieName, cookieOptions);
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
};
|