@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
package/src/session.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session shapes.
|
|
3
|
+
*
|
|
4
|
+
* `SessionPayloadV1` is the sealed cookie content (internal — carries the
|
|
5
|
+
* access/refresh tokens). `Session` is the public view handed to application
|
|
6
|
+
* code: it deliberately omits the refresh token and the raw ID token so the
|
|
7
|
+
* SDK's public surface cannot leak long-lived credentials into UI code
|
|
8
|
+
* (design.md §32.2 "UIへsecretを埋め込まない").
|
|
9
|
+
*
|
|
10
|
+
* The payload guard is hand-rolled (no zod in this package — the dependency
|
|
11
|
+
* budget is fixed) and validates every field after unsealing; anything that
|
|
12
|
+
* does not conform is treated as an invalid cookie and fails closed.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export interface SessionUser {
|
|
16
|
+
readonly sub: string;
|
|
17
|
+
readonly name?: string;
|
|
18
|
+
readonly email?: string;
|
|
19
|
+
readonly emailVerified?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface Session {
|
|
23
|
+
readonly user: SessionUser;
|
|
24
|
+
readonly accessToken: string;
|
|
25
|
+
/** Epoch seconds at which the access token expires. */
|
|
26
|
+
readonly accessTokenExpiresAt: number;
|
|
27
|
+
readonly scope: string;
|
|
28
|
+
/** Epoch seconds at which the BFF session itself expires. */
|
|
29
|
+
readonly sessionExpiresAt: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SessionPayloadV1 {
|
|
33
|
+
readonly v: 1;
|
|
34
|
+
readonly user: SessionUser;
|
|
35
|
+
readonly accessToken: string;
|
|
36
|
+
readonly accessTokenExpiresAt: number;
|
|
37
|
+
readonly refreshToken?: string;
|
|
38
|
+
readonly idToken?: string;
|
|
39
|
+
readonly scope: string;
|
|
40
|
+
readonly createdAt: number;
|
|
41
|
+
readonly expiresAt: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
45
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
46
|
+
|
|
47
|
+
const isSessionUser = (value: unknown): value is SessionUser => {
|
|
48
|
+
if (!isRecord(value)) return false;
|
|
49
|
+
if (typeof value.sub !== "string" || value.sub.length === 0) return false;
|
|
50
|
+
if (value.name !== undefined && typeof value.name !== "string") return false;
|
|
51
|
+
if (value.email !== undefined && typeof value.email !== "string") return false;
|
|
52
|
+
if (value.emailVerified !== undefined && typeof value.emailVerified !== "boolean") return false;
|
|
53
|
+
return true;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export const isSessionPayload = (value: unknown): value is SessionPayloadV1 => {
|
|
57
|
+
if (!isRecord(value)) return false;
|
|
58
|
+
if (value.v !== 1) return false;
|
|
59
|
+
if (!isSessionUser(value.user)) return false;
|
|
60
|
+
if (typeof value.accessToken !== "string" || value.accessToken.length === 0) return false;
|
|
61
|
+
if (typeof value.accessTokenExpiresAt !== "number") return false;
|
|
62
|
+
if (typeof value.scope !== "string") return false;
|
|
63
|
+
if (typeof value.createdAt !== "number" || typeof value.expiresAt !== "number") return false;
|
|
64
|
+
if (value.refreshToken !== undefined && typeof value.refreshToken !== "string") return false;
|
|
65
|
+
if (value.idToken !== undefined && typeof value.idToken !== "string") return false;
|
|
66
|
+
return true;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Strips long-lived credentials before the session reaches application code. */
|
|
70
|
+
export const toPublicSession = (payload: SessionPayloadV1): Session => ({
|
|
71
|
+
user: payload.user,
|
|
72
|
+
accessToken: payload.accessToken,
|
|
73
|
+
accessTokenExpiresAt: payload.accessTokenExpiresAt,
|
|
74
|
+
scope: payload.scope,
|
|
75
|
+
sessionExpiresAt: payload.expiresAt,
|
|
76
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
import { verifyWebhook } from "./index.js";
|
|
3
|
+
|
|
4
|
+
const SECRET = "whsec_docs_vector_fixed_secret";
|
|
5
|
+
const TIMESTAMP_SECONDS = 1_700_000_000;
|
|
6
|
+
const RAW_BODY =
|
|
7
|
+
'{"eventId":"evt_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","occurredAt":"2023-11-14T22:13:20.000Z","payload":{"maskedEmail":"u***@e***","method":"email_otp","userId":"usr_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"trace":{"requestId":"req_docs_vector"},"type":"user.created","version":1,"workspaceId":"wsp_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}';
|
|
8
|
+
const HEADERS = {
|
|
9
|
+
"X-Auth-Event-Id": "evt_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
10
|
+
"X-Auth-Timestamp": "1700000000",
|
|
11
|
+
"X-Auth-Signature": "v1=8656ce0fa8263cc2c29776b29cff567c276d9d64faa04cd99cb26721e18ded96",
|
|
12
|
+
"content-type": "application/json",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const verifyAt = (input: {
|
|
16
|
+
readonly headers?: Headers | Readonly<Record<string, string>>;
|
|
17
|
+
readonly rawBody?: string;
|
|
18
|
+
readonly secret?: string | readonly string[];
|
|
19
|
+
readonly nowSeconds?: number;
|
|
20
|
+
}) =>
|
|
21
|
+
verifyWebhook({
|
|
22
|
+
headers: input.headers ?? HEADERS,
|
|
23
|
+
rawBody: input.rawBody ?? RAW_BODY,
|
|
24
|
+
secret: input.secret ?? SECRET,
|
|
25
|
+
clock: () => input.nowSeconds ?? TIMESTAMP_SECONDS,
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe("verifyWebhook", () => {
|
|
29
|
+
test("verifies the hard-coded request produced by buildDeliveryRequest", async () => {
|
|
30
|
+
const result = await verifyAt({ headers: new Headers(HEADERS) });
|
|
31
|
+
|
|
32
|
+
expect(result).toEqual({
|
|
33
|
+
type: "Success",
|
|
34
|
+
value: {
|
|
35
|
+
eventId: "evt_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
36
|
+
timestampSeconds: TIMESTAMP_SECONDS,
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("accepts case-insensitive header names in a plain record", async () => {
|
|
42
|
+
const headers = Object.fromEntries(
|
|
43
|
+
Object.entries(HEADERS).map(([key, value]) => [key.toLowerCase(), value]),
|
|
44
|
+
);
|
|
45
|
+
const result = await verifyAt({ headers });
|
|
46
|
+
|
|
47
|
+
expect(result.type).toBe("Success");
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("rejects a changed raw body and a wrong secret", async () => {
|
|
51
|
+
const tampered = await verifyAt({ rawBody: `${RAW_BODY} ` });
|
|
52
|
+
const wrongSecret = await verifyAt({ secret: "whsec_wrong" });
|
|
53
|
+
|
|
54
|
+
expect(tampered).toEqual({ type: "Failure", error: { type: "signature_mismatch" } });
|
|
55
|
+
expect(wrongSecret).toEqual({ type: "Failure", error: { type: "signature_mismatch" } });
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("rejects timestamps more than the default tolerance behind or ahead", async () => {
|
|
59
|
+
const stale = await verifyAt({ nowSeconds: TIMESTAMP_SECONDS + 301 });
|
|
60
|
+
const future = await verifyAt({ nowSeconds: TIMESTAMP_SECONDS - 301 });
|
|
61
|
+
|
|
62
|
+
expect(stale).toEqual({
|
|
63
|
+
type: "Failure",
|
|
64
|
+
error: { type: "timestamp_too_old", ageSeconds: 301, toleranceSeconds: 300 },
|
|
65
|
+
});
|
|
66
|
+
expect(future).toEqual({
|
|
67
|
+
type: "Failure",
|
|
68
|
+
error: { type: "timestamp_in_future", skewSeconds: 301, toleranceSeconds: 300 },
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
test("accepts both exact tolerance boundaries", async () => {
|
|
73
|
+
const oldestAccepted = await verifyAt({ nowSeconds: TIMESTAMP_SECONDS + 300 });
|
|
74
|
+
const furthestFutureAccepted = await verifyAt({ nowSeconds: TIMESTAMP_SECONDS - 300 });
|
|
75
|
+
|
|
76
|
+
expect(oldestAccepted.type).toBe("Success");
|
|
77
|
+
expect(furthestFutureAccepted.type).toBe("Success");
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("reports each required header when absent", async () => {
|
|
81
|
+
for (const header of ["X-Auth-Event-Id", "X-Auth-Timestamp", "X-Auth-Signature"]) {
|
|
82
|
+
const headers = Object.fromEntries(Object.entries(HEADERS).filter(([key]) => key !== header));
|
|
83
|
+
const result = await verifyAt({ headers });
|
|
84
|
+
|
|
85
|
+
expect(result).toEqual({ type: "Failure", error: { type: "missing_header", header } });
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("tries each supplied secret during rotation", async () => {
|
|
90
|
+
const result = await verifyAt({ secret: ["whsec_previous", SECRET] });
|
|
91
|
+
const noMatch = await verifyAt({ secret: ["whsec_previous", "whsec_other"] });
|
|
92
|
+
|
|
93
|
+
expect(result.type).toBe("Success");
|
|
94
|
+
expect(noMatch).toEqual({ type: "Failure", error: { type: "signature_mismatch" } });
|
|
95
|
+
});
|
|
96
|
+
});
|
package/src/webhook.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { Result, type ResultAsync } from "./result.js";
|
|
2
|
+
import { timingSafeEqual } from "./security.js";
|
|
3
|
+
|
|
4
|
+
const EVENT_ID_HEADER = "X-Auth-Event-Id";
|
|
5
|
+
const TIMESTAMP_HEADER = "X-Auth-Timestamp";
|
|
6
|
+
const SIGNATURE_HEADER = "X-Auth-Signature";
|
|
7
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
8
|
+
const TIMESTAMP_PATTERN = /^\d+$/;
|
|
9
|
+
const SIGNATURE_PATTERN = /^v1=([0-9a-f]+)$/;
|
|
10
|
+
const textEncoder = new TextEncoder();
|
|
11
|
+
|
|
12
|
+
export type WebhookVerificationHeaders = Headers | Readonly<Record<string, string>>;
|
|
13
|
+
|
|
14
|
+
export interface VerifyWebhookInput {
|
|
15
|
+
readonly headers: WebhookVerificationHeaders;
|
|
16
|
+
/** Exact request body text, read before any JSON parsing or re-serialization. */
|
|
17
|
+
readonly rawBody: string;
|
|
18
|
+
/** One active signing secret, or all candidate secrets during rotation. */
|
|
19
|
+
readonly secret: string | readonly string[];
|
|
20
|
+
/** Maximum accepted age or future clock skew in seconds; defaults to 300. */
|
|
21
|
+
readonly toleranceSeconds?: number;
|
|
22
|
+
/** Injectable clock returning Unix seconds; defaults to the current time. */
|
|
23
|
+
readonly clock?: () => number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface VerifiedWebhook {
|
|
27
|
+
readonly eventId: string;
|
|
28
|
+
readonly timestampSeconds: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type WebhookVerificationError =
|
|
32
|
+
| { readonly type: "missing_header"; readonly header: string }
|
|
33
|
+
| { readonly type: "malformed_signature_header" }
|
|
34
|
+
| { readonly type: "malformed_timestamp_header" }
|
|
35
|
+
| {
|
|
36
|
+
readonly type: "timestamp_too_old";
|
|
37
|
+
readonly ageSeconds: number;
|
|
38
|
+
readonly toleranceSeconds: number;
|
|
39
|
+
}
|
|
40
|
+
| {
|
|
41
|
+
readonly type: "timestamp_in_future";
|
|
42
|
+
readonly skewSeconds: number;
|
|
43
|
+
readonly toleranceSeconds: number;
|
|
44
|
+
}
|
|
45
|
+
| { readonly type: "signature_mismatch" }
|
|
46
|
+
| { readonly type: "crypto_operation_failed" };
|
|
47
|
+
|
|
48
|
+
const findHeader = (headers: WebhookVerificationHeaders, name: string): string | undefined => {
|
|
49
|
+
if ("get" in headers && typeof headers.get === "function") {
|
|
50
|
+
return headers.get(name) ?? undefined;
|
|
51
|
+
}
|
|
52
|
+
const target = name.toLowerCase();
|
|
53
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
54
|
+
if (key.toLowerCase() === target) return value;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const hmacSha256Hex = Result.fn({
|
|
60
|
+
try: async (input: {
|
|
61
|
+
readonly secret: string;
|
|
62
|
+
readonly timestamp: string;
|
|
63
|
+
readonly rawBody: string;
|
|
64
|
+
}): Promise<string> => {
|
|
65
|
+
const secretBytes: Uint8Array<ArrayBuffer> = new Uint8Array(textEncoder.encode(input.secret));
|
|
66
|
+
const key = await crypto.subtle.importKey(
|
|
67
|
+
"raw",
|
|
68
|
+
secretBytes,
|
|
69
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
70
|
+
false,
|
|
71
|
+
["sign"],
|
|
72
|
+
);
|
|
73
|
+
const payloadBytes: Uint8Array<ArrayBuffer> = new Uint8Array(
|
|
74
|
+
textEncoder.encode(`${input.timestamp}.${input.rawBody}`),
|
|
75
|
+
);
|
|
76
|
+
const signature = await crypto.subtle.sign("HMAC", key, payloadBytes);
|
|
77
|
+
const signatureBytes = new Uint8Array(signature);
|
|
78
|
+
let hex = "";
|
|
79
|
+
for (const byte of signatureBytes) hex += byte.toString(16).padStart(2, "0");
|
|
80
|
+
return hex;
|
|
81
|
+
},
|
|
82
|
+
catch: (): WebhookVerificationError => ({ type: "crypto_operation_failed" }),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Verifies a Zeroword customer webhook using only WebCrypto. Preserve and pass
|
|
87
|
+
* the raw body as received; parsing and serializing JSON changes signed bytes.
|
|
88
|
+
*/
|
|
89
|
+
export const verifyWebhook = async (
|
|
90
|
+
input: VerifyWebhookInput,
|
|
91
|
+
): ResultAsync<VerifiedWebhook, WebhookVerificationError> => {
|
|
92
|
+
const eventId = findHeader(input.headers, EVENT_ID_HEADER);
|
|
93
|
+
if (eventId === undefined || eventId.length === 0) {
|
|
94
|
+
return Result.fail({ type: "missing_header", header: EVENT_ID_HEADER });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const timestampHeader = findHeader(input.headers, TIMESTAMP_HEADER);
|
|
98
|
+
if (timestampHeader === undefined || timestampHeader.length === 0) {
|
|
99
|
+
return Result.fail({ type: "missing_header", header: TIMESTAMP_HEADER });
|
|
100
|
+
}
|
|
101
|
+
if (!TIMESTAMP_PATTERN.test(timestampHeader)) {
|
|
102
|
+
return Result.fail({ type: "malformed_timestamp_header" });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const signatureHeader = findHeader(input.headers, SIGNATURE_HEADER);
|
|
106
|
+
if (signatureHeader === undefined || signatureHeader.length === 0) {
|
|
107
|
+
return Result.fail({ type: "missing_header", header: SIGNATURE_HEADER });
|
|
108
|
+
}
|
|
109
|
+
const signatureMatch = SIGNATURE_PATTERN.exec(signatureHeader);
|
|
110
|
+
const providedSignature = signatureMatch?.[1];
|
|
111
|
+
if (providedSignature === undefined) {
|
|
112
|
+
return Result.fail({ type: "malformed_signature_header" });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const timestampSeconds = Number.parseInt(timestampHeader, 10);
|
|
116
|
+
const toleranceSeconds = input.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
117
|
+
const nowSeconds = input.clock?.() ?? Math.floor(Date.now() / 1000);
|
|
118
|
+
|
|
119
|
+
if (timestampSeconds < nowSeconds - toleranceSeconds) {
|
|
120
|
+
return Result.fail({
|
|
121
|
+
type: "timestamp_too_old",
|
|
122
|
+
ageSeconds: nowSeconds - timestampSeconds,
|
|
123
|
+
toleranceSeconds,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (timestampSeconds > nowSeconds + toleranceSeconds) {
|
|
127
|
+
return Result.fail({
|
|
128
|
+
type: "timestamp_in_future",
|
|
129
|
+
skewSeconds: timestampSeconds - nowSeconds,
|
|
130
|
+
toleranceSeconds,
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const secretCount = typeof input.secret === "string" ? 1 : input.secret.length;
|
|
135
|
+
let matched = false;
|
|
136
|
+
for (let index = 0; index < secretCount; index += 1) {
|
|
137
|
+
const secret = typeof input.secret === "string" ? input.secret : input.secret[index];
|
|
138
|
+
if (secret === undefined) continue;
|
|
139
|
+
|
|
140
|
+
const expected = await hmacSha256Hex({
|
|
141
|
+
secret,
|
|
142
|
+
timestamp: timestampHeader,
|
|
143
|
+
rawBody: input.rawBody,
|
|
144
|
+
});
|
|
145
|
+
if (Result.isFailure(expected)) return expected;
|
|
146
|
+
matched = timingSafeEqual(expected.value, providedSignature) || matched;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (!matched) return Result.fail({ type: "signature_mismatch" });
|
|
150
|
+
return Result.succeed({ eventId, timestampSeconds });
|
|
151
|
+
};
|