@zenauth/node 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ZenAuth contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,122 @@
1
- # Temporary Holding Version
1
+ # @zenauth/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-side helpers for [ZenAuth](https://github.com). Your frontend signs users in with `@zenauth/react`, which gives it an **access token**. Your backend must never trust that token blindly. This package verifies it.
4
+
5
+ - Verifies the signature against your ZenAuth server's public keys (JWKS, cached and rotated automatically)
6
+ - Checks issuer and expiry, accepts **RS256 only**, and (optionally) that the token was issued to **your** app
7
+ - Fetches the user's profile (name, email) when you need it
8
+ - Works in any Node 18+ backend: Express, Fastify, Next.js route handlers, tRPC, Hono, ...
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install @zenauth/node
14
+ ```
15
+
16
+ ## Use
17
+
18
+ Create the verifier **once** at startup so the public keys stay cached.
19
+
20
+ ```ts
21
+ import { createZenAuth, getBearerToken, ZenAuthTokenError } from "@zenauth/node";
22
+
23
+ export const zenauth = createZenAuth({
24
+ issuer: process.env.ZENAUTH_ISSUER!, // base URL of the ZenAuth API
25
+ clientId: process.env.ZENAUTH_CLIENT_ID!, // your application's client ID
26
+ });
27
+ ```
28
+
29
+ ### Express
30
+
31
+ ```ts
32
+ app.use(async (req, res, next) => {
33
+ try {
34
+ const { userId } = await zenauth.verifyToken(getBearerToken(req.headers.authorization));
35
+ req.userId = userId; // ZenAuth user id
36
+ next();
37
+ } catch (err) {
38
+ if (err instanceof ZenAuthTokenError) return res.status(401).json({ error: err.code });
39
+ next(err);
40
+ }
41
+ });
42
+ ```
43
+
44
+ ### tRPC context
45
+
46
+ ```ts
47
+ export async function createContext({ req }: { req: Request }) {
48
+ const token = getBearerToken(req.headers.get("authorization"));
49
+ try {
50
+ const { userId } = await zenauth.verifyToken(token);
51
+ return { zenAuthUserId: userId };
52
+ } catch {
53
+ return { zenAuthUserId: null };
54
+ }
55
+ }
56
+ ```
57
+
58
+ ### Sending the token from the browser
59
+
60
+ ```tsx
61
+ import { useZenAuth } from "@zenauth/react";
62
+
63
+ const { getAccessToken } = useZenAuth();
64
+ const token = await getAccessToken(); // refreshed automatically when about to expire
65
+ fetch("/api/forms", { headers: { authorization: `Bearer ${token}` } });
66
+ ```
67
+
68
+ ### Linking ZenAuth users to your own users table
69
+
70
+ The token only carries the user id (`sub`). Use it as the key to your own user row, and call `getUserInfo` once when you first see a new user:
71
+
72
+ ```ts
73
+ const verified = await zenauth.verifyToken(token);
74
+ let user = await db.findUserByZenAuthId(verified.userId);
75
+ if (!user) {
76
+ const info = await zenauth.getUserInfo(token); // { sub, name, email, email_verified }
77
+ user = await db.createUser({ zenAuthId: info.sub, name: info.name, email: info.email });
78
+ }
79
+ ```
80
+
81
+ ## API
82
+
83
+ | Export | Description |
84
+ | --- | --- |
85
+ | `createZenAuth({ issuer, clientId?, clockToleranceSec? })` | Returns `{ verifyToken, getUserInfo, issuer }`. |
86
+ | `verifyToken(token)` | Resolves to `{ userId, clientId, scopes, expiresAt, claims }`, or throws `ZenAuthTokenError`. |
87
+ | `getUserInfo(accessToken)` | Verifies the token, then returns `{ sub, name?, email?, email_verified? }` (depends on granted scopes). |
88
+ | `getBearerToken(header)` | Pulls the token out of an `Authorization: Bearer ...` header, or `null`. |
89
+ | `ZenAuthTokenError` | `error.code` is one of `missing_token`, `invalid_token`, `token_expired`, `wrong_client`, `userinfo_failed`. |
90
+
91
+ ## Roles, organizations and webhooks
92
+
93
+ `verifyToken` and `getUserInfo` include `role` and, with the `organizations` scope, `orgs`.
94
+
95
+ `verifyWebhook({ payload, signature, secret, toleranceSec? })` checks the `ZenAuth-Signature` header and returns
96
+ the event, or throws `ZenAuthWebhookError`. Pass the raw request body, not parsed JSON:
97
+
98
+ ```ts
99
+ app.post("/webhooks/zenauth", express.raw({ type: "application/json" }), (req, res) => {
100
+ const event = verifyWebhook({
101
+ payload: req.body,
102
+ signature: req.get("zenauth-signature"),
103
+ secret: process.env.ZENAUTH_WEBHOOK_SECRET!,
104
+ });
105
+ res.sendStatus(200);
106
+ });
107
+ ```
108
+
109
+ ## Security notes
110
+
111
+ - Always pass `clientId`. Without it, a valid token minted for a different ZenAuth application would be accepted.
112
+ - Only RS256 is accepted. Tokens using `HS256` or `alg: none` are rejected.
113
+ - Treat `getUserInfo().email` as verified only when `email_verified` is `true`.
114
+ - Keep your own authorization rules (who can see which form). This package only proves **who** the user is.
115
+
116
+ ## Develop
117
+
118
+ ```bash
119
+ pnpm --filter @zenauth/node test
120
+ pnpm --filter @zenauth/node check-types
121
+ pnpm --filter @zenauth/node build
122
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ZenAuthTokenError: () => ZenAuthTokenError,
24
+ ZenAuthWebhookError: () => ZenAuthWebhookError,
25
+ createZenAuth: () => createZenAuth,
26
+ getBearerToken: () => getBearerToken,
27
+ verifyWebhook: () => verifyWebhook
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+ var import_node_crypto = require("crypto");
31
+ var import_jose = require("jose");
32
+ var ZenAuthTokenError = class extends Error {
33
+ code;
34
+ constructor(code, message, options) {
35
+ super(message, options);
36
+ this.name = "ZenAuthTokenError";
37
+ this.code = code;
38
+ }
39
+ };
40
+ var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
41
+ function getBearerToken(authorizationHeader) {
42
+ if (!authorizationHeader) return null;
43
+ const match = /^Bearer\s+(\S+)$/i.exec(authorizationHeader.trim());
44
+ return match?.[1] ?? null;
45
+ }
46
+ function createZenAuth(options) {
47
+ const issuer = stripTrailingSlash(options.issuer);
48
+ const keys = options.keys ?? (0, import_jose.createRemoteJWKSet)(new URL(`${issuer}/.well-known/jwks.json`));
49
+ async function verifyToken(token) {
50
+ if (!token) throw new ZenAuthTokenError("missing_token", "No access token provided");
51
+ let claims;
52
+ try {
53
+ const { payload } = await (0, import_jose.jwtVerify)(token, keys, {
54
+ issuer,
55
+ algorithms: ["RS256"],
56
+ clockTolerance: options.clockToleranceSec ?? 5
57
+ });
58
+ claims = payload;
59
+ } catch (err) {
60
+ if (err instanceof import_jose.errors.JWTExpired) {
61
+ throw new ZenAuthTokenError("token_expired", "Access token has expired", { cause: err });
62
+ }
63
+ throw new ZenAuthTokenError("invalid_token", "Access token is invalid", { cause: err });
64
+ }
65
+ const sub = typeof claims.sub === "string" ? claims.sub : "";
66
+ const aud = Array.isArray(claims.aud) ? claims.aud[0] : claims.aud;
67
+ const tokenClient = typeof claims.client_id === "string" ? claims.client_id : typeof aud === "string" ? aud : "";
68
+ if (!sub || !tokenClient) {
69
+ throw new ZenAuthTokenError("invalid_token", "Token is missing required claims");
70
+ }
71
+ if (options.clientId && tokenClient !== options.clientId) {
72
+ throw new ZenAuthTokenError("wrong_client", "Token was not issued to this application");
73
+ }
74
+ return {
75
+ userId: sub,
76
+ clientId: tokenClient,
77
+ ...typeof claims.role === "string" && { role: claims.role },
78
+ ...Array.isArray(claims.orgs) && { orgs: claims.orgs },
79
+ scopes: typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [],
80
+ expiresAt: typeof claims.exp === "number" ? claims.exp : 0,
81
+ claims
82
+ };
83
+ }
84
+ async function getUserInfo(accessToken) {
85
+ await verifyToken(accessToken);
86
+ let res;
87
+ try {
88
+ res = await fetch(`${issuer}/o/userinfo`, { headers: { authorization: `Bearer ${accessToken}` } });
89
+ } catch (err) {
90
+ throw new ZenAuthTokenError("userinfo_failed", "Could not reach ZenAuth", { cause: err });
91
+ }
92
+ if (!res.ok) {
93
+ throw new ZenAuthTokenError("userinfo_failed", `ZenAuth userinfo returned ${res.status}`);
94
+ }
95
+ return await res.json();
96
+ }
97
+ return { verifyToken, getUserInfo, issuer };
98
+ }
99
+ var ZenAuthWebhookError = class extends Error {
100
+ constructor(message) {
101
+ super(message);
102
+ this.name = "ZenAuthWebhookError";
103
+ }
104
+ };
105
+ function verifyWebhook(input) {
106
+ const body = typeof input.payload === "string" ? input.payload : Buffer.from(input.payload).toString("utf8");
107
+ const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(input.signature ?? "");
108
+ if (!match) throw new ZenAuthWebhookError("Missing or malformed ZenAuth-Signature header");
109
+ const [, timestamp, received] = match;
110
+ if (!input.secret) throw new ZenAuthWebhookError("Webhook secret is not configured");
111
+ const expected = (0, import_node_crypto.createHmac)("sha256", input.secret).update(`${timestamp}.${body}`).digest();
112
+ if (!(0, import_node_crypto.timingSafeEqual)(expected, Buffer.from(received, "hex"))) {
113
+ throw new ZenAuthWebhookError("Webhook signature does not match");
114
+ }
115
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > (input.toleranceSec ?? 300)) {
116
+ throw new ZenAuthWebhookError("Webhook signature is too old");
117
+ }
118
+ return JSON.parse(body);
119
+ }
120
+ // Annotate the CommonJS export names for ESM import in node:
121
+ 0 && (module.exports = {
122
+ ZenAuthTokenError,
123
+ ZenAuthWebhookError,
124
+ createZenAuth,
125
+ getBearerToken,
126
+ verifyWebhook
127
+ });
128
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport { createRemoteJWKSet, errors as joseErrors, jwtVerify, type JWTVerifyGetKey } from \"jose\";\n\nexport interface ZenAuthVerifierOptions {\n /** Base URL of the ZenAuth API, e.g. `https://api.zenauth.example.com`. Must match the token `iss`. */\n issuer: string;\n /**\n * Your application's client ID. When set, tokens issued to any other application are rejected.\n * Strongly recommended: without it, a token minted for a different app would be accepted.\n */\n clientId?: string;\n /** Allowed clock drift in seconds when checking `exp` / `nbf`. Default 5. */\n clockToleranceSec?: number;\n /** Advanced: custom key resolver (used by tests). Defaults to the issuer's JWKS endpoint. */\n keys?: JWTVerifyGetKey;\n}\n\nexport interface Organization {\n id: string;\n slug: string;\n name: string;\n role: \"owner\" | \"admin\" | \"member\";\n}\n\nexport interface VerifiedToken {\n /** The user's role in your app, if one applies. */\n role?: string;\n /** The user's teams. Present when the `organizations` scope was granted. */\n orgs?: Organization[];\n /** ZenAuth user id. Stable: use it as the foreign key to your own user row. */\n userId: string;\n /** Client ID the token was issued to. */\n clientId: string;\n /** Granted scopes, e.g. `[\"openid\", \"profile\", \"email\"]`. */\n scopes: string[];\n /** Expiry as a Unix timestamp (seconds). */\n expiresAt: number;\n /** All claims in the token. */\n claims: Record<string, unknown>;\n}\n\nexport interface UserInfo {\n sub: string;\n /** Present when the `profile` scope was granted. */\n name?: string;\n /** Present when the `email` scope was granted. */\n email?: string;\n email_verified?: boolean;\n role?: string;\n orgs?: Organization[];\n}\n\nexport type TokenErrorCode =\n | \"missing_token\"\n | \"invalid_token\"\n | \"token_expired\"\n | \"wrong_client\"\n | \"userinfo_failed\";\n\nexport class ZenAuthTokenError extends Error {\n readonly code: TokenErrorCode;\n constructor(code: TokenErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"ZenAuthTokenError\";\n this.code = code;\n }\n}\n\nconst stripTrailingSlash = (url: string) => url.replace(/\\/+$/, \"\");\n\n/**\n * Extracts the token from an `Authorization: Bearer <token>` header value.\n * Returns `null` if the header is absent or not a Bearer credential.\n */\nexport function getBearerToken(authorizationHeader: string | null | undefined): string | null {\n if (!authorizationHeader) return null;\n const match = /^Bearer\\s+(\\S+)$/i.exec(authorizationHeader.trim());\n return match?.[1] ?? null;\n}\n\n/**\n * Creates a reusable verifier. Create it ONCE at startup: it caches the issuer's public keys\n * (and refreshes them automatically when ZenAuth rotates its signing key).\n *\n * ```ts\n * const zenauth = createZenAuth({ issuer: process.env.ZENAUTH_ISSUER!, clientId: process.env.ZENAUTH_CLIENT_ID! });\n * const { userId } = await zenauth.verifyToken(getBearerToken(req.headers.authorization));\n * ```\n */\nexport function createZenAuth(options: ZenAuthVerifierOptions) {\n const issuer = stripTrailingSlash(options.issuer);\n const keys = options.keys ?? createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));\n\n /**\n * Verifies signature (RS256 only), issuer and expiry, and that the token was issued to your app.\n * Throws {@link ZenAuthTokenError} on any failure. Never trusts an unverified token.\n */\n async function verifyToken(token: string | null | undefined): Promise<VerifiedToken> {\n if (!token) throw new ZenAuthTokenError(\"missing_token\", \"No access token provided\");\n\n let claims: Record<string, unknown>;\n try {\n const { payload } = await jwtVerify(token, keys, {\n issuer,\n algorithms: [\"RS256\"],\n clockTolerance: options.clockToleranceSec ?? 5,\n });\n claims = payload as Record<string, unknown>;\n } catch (err) {\n if (err instanceof joseErrors.JWTExpired) {\n throw new ZenAuthTokenError(\"token_expired\", \"Access token has expired\", { cause: err });\n }\n throw new ZenAuthTokenError(\"invalid_token\", \"Access token is invalid\", { cause: err });\n }\n\n const sub = typeof claims.sub === \"string\" ? claims.sub : \"\";\n // Access tokens carry `client_id`; ID tokens carry `aud`. Accept either.\n const aud = Array.isArray(claims.aud) ? claims.aud[0] : claims.aud;\n const tokenClient =\n typeof claims.client_id === \"string\" ? claims.client_id : typeof aud === \"string\" ? aud : \"\";\n\n if (!sub || !tokenClient) {\n throw new ZenAuthTokenError(\"invalid_token\", \"Token is missing required claims\");\n }\n if (options.clientId && tokenClient !== options.clientId) {\n throw new ZenAuthTokenError(\"wrong_client\", \"Token was not issued to this application\");\n }\n\n return {\n userId: sub,\n clientId: tokenClient,\n ...(typeof claims.role === \"string\" && { role: claims.role }),\n ...(Array.isArray(claims.orgs) && { orgs: claims.orgs as Organization[] }),\n scopes: typeof claims.scope === \"string\" ? claims.scope.split(\" \").filter(Boolean) : [],\n expiresAt: typeof claims.exp === \"number\" ? claims.exp : 0,\n claims,\n };\n }\n\n /**\n * Fetches the user's profile (name, email, email_verified) from ZenAuth.\n * Access tokens only carry the user id, so call this once when you first create your local user row.\n */\n async function getUserInfo(accessToken: string): Promise<UserInfo> {\n await verifyToken(accessToken);\n let res: Response;\n try {\n res = await fetch(`${issuer}/o/userinfo`, { headers: { authorization: `Bearer ${accessToken}` } });\n } catch (err) {\n throw new ZenAuthTokenError(\"userinfo_failed\", \"Could not reach ZenAuth\", { cause: err });\n }\n if (!res.ok) {\n throw new ZenAuthTokenError(\"userinfo_failed\", `ZenAuth userinfo returned ${res.status}`);\n }\n return (await res.json()) as UserInfo;\n }\n\n return { verifyToken, getUserInfo, issuer };\n}\n\nexport type ZenAuth = ReturnType<typeof createZenAuth>;\n\n// ── Webhooks ────────────────────────────────────────────────\nexport interface WebhookEvent {\n /** Unique per delivery attempt group: store it to ignore retries you already handled. */\n id: string;\n type: \"user.created\" | \"user.login\" | \"user.deleted\" | \"ping\";\n client_id: string;\n created_at: string;\n data: Record<string, unknown>;\n}\n\nexport class ZenAuthWebhookError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ZenAuthWebhookError\";\n }\n}\n\n/**\n * Checks the `ZenAuth-Signature` header and returns the event. Pass the RAW request body: re-serialised\n * JSON does not match the signature.\n *\n * ```ts\n * app.post(\"/webhooks/zenauth\", express.raw({ type: \"application/json\" }), (req, res) => {\n * const event = verifyWebhook({ payload: req.body, signature: req.get(\"zenauth-signature\"), secret });\n * res.sendStatus(200);\n * });\n * ```\n */\nexport function verifyWebhook(input: {\n payload: string | Uint8Array;\n signature: string | null | undefined;\n secret: string;\n /** Oldest accepted signature, to stop replays. Default 300 seconds. */\n toleranceSec?: number;\n}): WebhookEvent {\n const body = typeof input.payload === \"string\" ? input.payload : Buffer.from(input.payload).toString(\"utf8\");\n const match = /^t=(\\d+),v1=([0-9a-f]{64})$/.exec(input.signature ?? \"\");\n if (!match) throw new ZenAuthWebhookError(\"Missing or malformed ZenAuth-Signature header\");\n const [, timestamp, received] = match as unknown as [string, string, string];\n\n if (!input.secret) throw new ZenAuthWebhookError(\"Webhook secret is not configured\");\n const expected = createHmac(\"sha256\", input.secret).update(`${timestamp}.${body}`).digest();\n if (!timingSafeEqual(expected, Buffer.from(received, \"hex\"))) {\n throw new ZenAuthWebhookError(\"Webhook signature does not match\");\n }\n if (Math.abs(Date.now() / 1000 - Number(timestamp)) > (input.toleranceSec ?? 300)) {\n throw new ZenAuthWebhookError(\"Webhook signature is too old\");\n }\n return JSON.parse(body) as WebhookEvent;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA4C;AAC5C,kBAA0F;AA0DnF,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAClC;AAAA,EACT,YAAY,MAAsB,SAAiB,SAA+B;AAChF,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,qBAAqB,CAAC,QAAgB,IAAI,QAAQ,QAAQ,EAAE;AAM3D,SAAS,eAAe,qBAA+D;AAC5F,MAAI,CAAC,oBAAqB,QAAO;AACjC,QAAM,QAAQ,oBAAoB,KAAK,oBAAoB,KAAK,CAAC;AACjE,SAAO,QAAQ,CAAC,KAAK;AACvB;AAWO,SAAS,cAAc,SAAiC;AAC7D,QAAM,SAAS,mBAAmB,QAAQ,MAAM;AAChD,QAAM,OAAO,QAAQ,YAAQ,gCAAmB,IAAI,IAAI,GAAG,MAAM,wBAAwB,CAAC;AAM1F,iBAAe,YAAY,OAA0D;AACnF,QAAI,CAAC,MAAO,OAAM,IAAI,kBAAkB,iBAAiB,0BAA0B;AAEnF,QAAI;AACJ,QAAI;AACF,YAAM,EAAE,QAAQ,IAAI,UAAM,uBAAU,OAAO,MAAM;AAAA,QAC/C;AAAA,QACA,YAAY,CAAC,OAAO;AAAA,QACpB,gBAAgB,QAAQ,qBAAqB;AAAA,MAC/C,CAAC;AACD,eAAS;AAAA,IACX,SAAS,KAAK;AACZ,UAAI,eAAe,YAAAA,OAAW,YAAY;AACxC,cAAM,IAAI,kBAAkB,iBAAiB,4BAA4B,EAAE,OAA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6B,IAAI,MAAM,EAAE;AAAA,IAC1F;AACA,WAAQ,MAAM,IAAI,KAAK;AAAA,EACzB;AAEA,SAAO,EAAE,aAAa,aAAa,OAAO;AAC5C;AAcO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAaO,SAAS,cAAc,OAMb;AACf,QAAM,OAAO,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU,OAAO,KAAK,MAAM,OAAO,EAAE,SAAS,MAAM;AAC3G,QAAM,QAAQ,8BAA8B,KAAK,MAAM,aAAa,EAAE;AACtE,MAAI,CAAC,MAAO,OAAM,IAAI,oBAAoB,+CAA+C;AACzF,QAAM,CAAC,EAAE,WAAW,QAAQ,IAAI;AAEhC,MAAI,CAAC,MAAM,OAAQ,OAAM,IAAI,oBAAoB,kCAAkC;AACnF,QAAM,eAAW,+BAAW,UAAU,MAAM,MAAM,EAAE,OAAO,GAAG,SAAS,IAAI,IAAI,EAAE,EAAE,OAAO;AAC1F,MAAI,KAAC,oCAAgB,UAAU,OAAO,KAAK,UAAU,KAAK,CAAC,GAAG;AAC5D,UAAM,IAAI,oBAAoB,kCAAkC;AAAA,EAClE;AACA,MAAI,KAAK,IAAI,KAAK,IAAI,IAAI,MAAO,OAAO,SAAS,CAAC,KAAK,MAAM,gBAAgB,MAAM;AACjF,UAAM,IAAI,oBAAoB,8BAA8B;AAAA,EAC9D;AACA,SAAO,KAAK,MAAM,IAAI;AACxB;","names":["joseErrors"]}
@@ -0,0 +1,105 @@
1
+ import { JWTVerifyGetKey } from 'jose';
2
+
3
+ interface ZenAuthVerifierOptions {
4
+ /** Base URL of the ZenAuth API, e.g. `https://api.zenauth.example.com`. Must match the token `iss`. */
5
+ issuer: string;
6
+ /**
7
+ * Your application's client ID. When set, tokens issued to any other application are rejected.
8
+ * Strongly recommended: without it, a token minted for a different app would be accepted.
9
+ */
10
+ clientId?: string;
11
+ /** Allowed clock drift in seconds when checking `exp` / `nbf`. Default 5. */
12
+ clockToleranceSec?: number;
13
+ /** Advanced: custom key resolver (used by tests). Defaults to the issuer's JWKS endpoint. */
14
+ keys?: JWTVerifyGetKey;
15
+ }
16
+ interface Organization {
17
+ id: string;
18
+ slug: string;
19
+ name: string;
20
+ role: "owner" | "admin" | "member";
21
+ }
22
+ interface VerifiedToken {
23
+ /** The user's role in your app, if one applies. */
24
+ role?: string;
25
+ /** The user's teams. Present when the `organizations` scope was granted. */
26
+ orgs?: Organization[];
27
+ /** ZenAuth user id. Stable: use it as the foreign key to your own user row. */
28
+ userId: string;
29
+ /** Client ID the token was issued to. */
30
+ clientId: string;
31
+ /** Granted scopes, e.g. `["openid", "profile", "email"]`. */
32
+ scopes: string[];
33
+ /** Expiry as a Unix timestamp (seconds). */
34
+ expiresAt: number;
35
+ /** All claims in the token. */
36
+ claims: Record<string, unknown>;
37
+ }
38
+ interface UserInfo {
39
+ sub: string;
40
+ /** Present when the `profile` scope was granted. */
41
+ name?: string;
42
+ /** Present when the `email` scope was granted. */
43
+ email?: string;
44
+ email_verified?: boolean;
45
+ role?: string;
46
+ orgs?: Organization[];
47
+ }
48
+ type TokenErrorCode = "missing_token" | "invalid_token" | "token_expired" | "wrong_client" | "userinfo_failed";
49
+ declare class ZenAuthTokenError extends Error {
50
+ readonly code: TokenErrorCode;
51
+ constructor(code: TokenErrorCode, message: string, options?: {
52
+ cause?: unknown;
53
+ });
54
+ }
55
+ /**
56
+ * Extracts the token from an `Authorization: Bearer <token>` header value.
57
+ * Returns `null` if the header is absent or not a Bearer credential.
58
+ */
59
+ declare function getBearerToken(authorizationHeader: string | null | undefined): string | null;
60
+ /**
61
+ * Creates a reusable verifier. Create it ONCE at startup: it caches the issuer's public keys
62
+ * (and refreshes them automatically when ZenAuth rotates its signing key).
63
+ *
64
+ * ```ts
65
+ * const zenauth = createZenAuth({ issuer: process.env.ZENAUTH_ISSUER!, clientId: process.env.ZENAUTH_CLIENT_ID! });
66
+ * const { userId } = await zenauth.verifyToken(getBearerToken(req.headers.authorization));
67
+ * ```
68
+ */
69
+ declare function createZenAuth(options: ZenAuthVerifierOptions): {
70
+ verifyToken: (token: string | null | undefined) => Promise<VerifiedToken>;
71
+ getUserInfo: (accessToken: string) => Promise<UserInfo>;
72
+ issuer: string;
73
+ };
74
+ type ZenAuth = ReturnType<typeof createZenAuth>;
75
+ interface WebhookEvent {
76
+ /** Unique per delivery attempt group: store it to ignore retries you already handled. */
77
+ id: string;
78
+ type: "user.created" | "user.login" | "user.deleted" | "ping";
79
+ client_id: string;
80
+ created_at: string;
81
+ data: Record<string, unknown>;
82
+ }
83
+ declare class ZenAuthWebhookError extends Error {
84
+ constructor(message: string);
85
+ }
86
+ /**
87
+ * Checks the `ZenAuth-Signature` header and returns the event. Pass the RAW request body: re-serialised
88
+ * JSON does not match the signature.
89
+ *
90
+ * ```ts
91
+ * app.post("/webhooks/zenauth", express.raw({ type: "application/json" }), (req, res) => {
92
+ * const event = verifyWebhook({ payload: req.body, signature: req.get("zenauth-signature"), secret });
93
+ * res.sendStatus(200);
94
+ * });
95
+ * ```
96
+ */
97
+ declare function verifyWebhook(input: {
98
+ payload: string | Uint8Array;
99
+ signature: string | null | undefined;
100
+ secret: string;
101
+ /** Oldest accepted signature, to stop replays. Default 300 seconds. */
102
+ toleranceSec?: number;
103
+ }): WebhookEvent;
104
+
105
+ export { type Organization, type TokenErrorCode, type UserInfo, type VerifiedToken, type WebhookEvent, type ZenAuth, ZenAuthTokenError, type ZenAuthVerifierOptions, ZenAuthWebhookError, createZenAuth, getBearerToken, verifyWebhook };
@@ -0,0 +1,105 @@
1
+ import { JWTVerifyGetKey } from 'jose';
2
+
3
+ interface ZenAuthVerifierOptions {
4
+ /** Base URL of the ZenAuth API, e.g. `https://api.zenauth.example.com`. Must match the token `iss`. */
5
+ issuer: string;
6
+ /**
7
+ * Your application's client ID. When set, tokens issued to any other application are rejected.
8
+ * Strongly recommended: without it, a token minted for a different app would be accepted.
9
+ */
10
+ clientId?: string;
11
+ /** Allowed clock drift in seconds when checking `exp` / `nbf`. Default 5. */
12
+ clockToleranceSec?: number;
13
+ /** Advanced: custom key resolver (used by tests). Defaults to the issuer's JWKS endpoint. */
14
+ keys?: JWTVerifyGetKey;
15
+ }
16
+ interface Organization {
17
+ id: string;
18
+ slug: string;
19
+ name: string;
20
+ role: "owner" | "admin" | "member";
21
+ }
22
+ interface VerifiedToken {
23
+ /** The user's role in your app, if one applies. */
24
+ role?: string;
25
+ /** The user's teams. Present when the `organizations` scope was granted. */
26
+ orgs?: Organization[];
27
+ /** ZenAuth user id. Stable: use it as the foreign key to your own user row. */
28
+ userId: string;
29
+ /** Client ID the token was issued to. */
30
+ clientId: string;
31
+ /** Granted scopes, e.g. `["openid", "profile", "email"]`. */
32
+ scopes: string[];
33
+ /** Expiry as a Unix timestamp (seconds). */
34
+ expiresAt: number;
35
+ /** All claims in the token. */
36
+ claims: Record<string, unknown>;
37
+ }
38
+ interface UserInfo {
39
+ sub: string;
40
+ /** Present when the `profile` scope was granted. */
41
+ name?: string;
42
+ /** Present when the `email` scope was granted. */
43
+ email?: string;
44
+ email_verified?: boolean;
45
+ role?: string;
46
+ orgs?: Organization[];
47
+ }
48
+ type TokenErrorCode = "missing_token" | "invalid_token" | "token_expired" | "wrong_client" | "userinfo_failed";
49
+ declare class ZenAuthTokenError extends Error {
50
+ readonly code: TokenErrorCode;
51
+ constructor(code: TokenErrorCode, message: string, options?: {
52
+ cause?: unknown;
53
+ });
54
+ }
55
+ /**
56
+ * Extracts the token from an `Authorization: Bearer <token>` header value.
57
+ * Returns `null` if the header is absent or not a Bearer credential.
58
+ */
59
+ declare function getBearerToken(authorizationHeader: string | null | undefined): string | null;
60
+ /**
61
+ * Creates a reusable verifier. Create it ONCE at startup: it caches the issuer's public keys
62
+ * (and refreshes them automatically when ZenAuth rotates its signing key).
63
+ *
64
+ * ```ts
65
+ * const zenauth = createZenAuth({ issuer: process.env.ZENAUTH_ISSUER!, clientId: process.env.ZENAUTH_CLIENT_ID! });
66
+ * const { userId } = await zenauth.verifyToken(getBearerToken(req.headers.authorization));
67
+ * ```
68
+ */
69
+ declare function createZenAuth(options: ZenAuthVerifierOptions): {
70
+ verifyToken: (token: string | null | undefined) => Promise<VerifiedToken>;
71
+ getUserInfo: (accessToken: string) => Promise<UserInfo>;
72
+ issuer: string;
73
+ };
74
+ type ZenAuth = ReturnType<typeof createZenAuth>;
75
+ interface WebhookEvent {
76
+ /** Unique per delivery attempt group: store it to ignore retries you already handled. */
77
+ id: string;
78
+ type: "user.created" | "user.login" | "user.deleted" | "ping";
79
+ client_id: string;
80
+ created_at: string;
81
+ data: Record<string, unknown>;
82
+ }
83
+ declare class ZenAuthWebhookError extends Error {
84
+ constructor(message: string);
85
+ }
86
+ /**
87
+ * Checks the `ZenAuth-Signature` header and returns the event. Pass the RAW request body: re-serialised
88
+ * JSON does not match the signature.
89
+ *
90
+ * ```ts
91
+ * app.post("/webhooks/zenauth", express.raw({ type: "application/json" }), (req, res) => {
92
+ * const event = verifyWebhook({ payload: req.body, signature: req.get("zenauth-signature"), secret });
93
+ * res.sendStatus(200);
94
+ * });
95
+ * ```
96
+ */
97
+ declare function verifyWebhook(input: {
98
+ payload: string | Uint8Array;
99
+ signature: string | null | undefined;
100
+ secret: string;
101
+ /** Oldest accepted signature, to stop replays. Default 300 seconds. */
102
+ toleranceSec?: number;
103
+ }): WebhookEvent;
104
+
105
+ export { type Organization, type TokenErrorCode, type UserInfo, type VerifiedToken, type WebhookEvent, type ZenAuth, ZenAuthTokenError, type ZenAuthVerifierOptions, ZenAuthWebhookError, createZenAuth, getBearerToken, verifyWebhook };
package/dist/index.js ADDED
@@ -0,0 +1,99 @@
1
+ // src/index.ts
2
+ import { createHmac, timingSafeEqual } from "crypto";
3
+ import { createRemoteJWKSet, errors as joseErrors, jwtVerify } from "jose";
4
+ var ZenAuthTokenError = class extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message, options);
8
+ this.name = "ZenAuthTokenError";
9
+ this.code = code;
10
+ }
11
+ };
12
+ var stripTrailingSlash = (url) => url.replace(/\/+$/, "");
13
+ function getBearerToken(authorizationHeader) {
14
+ if (!authorizationHeader) return null;
15
+ const match = /^Bearer\s+(\S+)$/i.exec(authorizationHeader.trim());
16
+ return match?.[1] ?? null;
17
+ }
18
+ function createZenAuth(options) {
19
+ const issuer = stripTrailingSlash(options.issuer);
20
+ const keys = options.keys ?? createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));
21
+ async function verifyToken(token) {
22
+ if (!token) throw new ZenAuthTokenError("missing_token", "No access token provided");
23
+ let claims;
24
+ try {
25
+ const { payload } = await jwtVerify(token, keys, {
26
+ issuer,
27
+ algorithms: ["RS256"],
28
+ clockTolerance: options.clockToleranceSec ?? 5
29
+ });
30
+ claims = payload;
31
+ } catch (err) {
32
+ if (err instanceof joseErrors.JWTExpired) {
33
+ throw new ZenAuthTokenError("token_expired", "Access token has expired", { cause: err });
34
+ }
35
+ throw new ZenAuthTokenError("invalid_token", "Access token is invalid", { cause: err });
36
+ }
37
+ const sub = typeof claims.sub === "string" ? claims.sub : "";
38
+ const aud = Array.isArray(claims.aud) ? claims.aud[0] : claims.aud;
39
+ const tokenClient = typeof claims.client_id === "string" ? claims.client_id : typeof aud === "string" ? aud : "";
40
+ if (!sub || !tokenClient) {
41
+ throw new ZenAuthTokenError("invalid_token", "Token is missing required claims");
42
+ }
43
+ if (options.clientId && tokenClient !== options.clientId) {
44
+ throw new ZenAuthTokenError("wrong_client", "Token was not issued to this application");
45
+ }
46
+ return {
47
+ userId: sub,
48
+ clientId: tokenClient,
49
+ ...typeof claims.role === "string" && { role: claims.role },
50
+ ...Array.isArray(claims.orgs) && { orgs: claims.orgs },
51
+ scopes: typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [],
52
+ expiresAt: typeof claims.exp === "number" ? claims.exp : 0,
53
+ claims
54
+ };
55
+ }
56
+ async function getUserInfo(accessToken) {
57
+ await verifyToken(accessToken);
58
+ let res;
59
+ try {
60
+ res = await fetch(`${issuer}/o/userinfo`, { headers: { authorization: `Bearer ${accessToken}` } });
61
+ } catch (err) {
62
+ throw new ZenAuthTokenError("userinfo_failed", "Could not reach ZenAuth", { cause: err });
63
+ }
64
+ if (!res.ok) {
65
+ throw new ZenAuthTokenError("userinfo_failed", `ZenAuth userinfo returned ${res.status}`);
66
+ }
67
+ return await res.json();
68
+ }
69
+ return { verifyToken, getUserInfo, issuer };
70
+ }
71
+ var ZenAuthWebhookError = class extends Error {
72
+ constructor(message) {
73
+ super(message);
74
+ this.name = "ZenAuthWebhookError";
75
+ }
76
+ };
77
+ function verifyWebhook(input) {
78
+ const body = typeof input.payload === "string" ? input.payload : Buffer.from(input.payload).toString("utf8");
79
+ const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(input.signature ?? "");
80
+ if (!match) throw new ZenAuthWebhookError("Missing or malformed ZenAuth-Signature header");
81
+ const [, timestamp, received] = match;
82
+ if (!input.secret) throw new ZenAuthWebhookError("Webhook secret is not configured");
83
+ const expected = createHmac("sha256", input.secret).update(`${timestamp}.${body}`).digest();
84
+ if (!timingSafeEqual(expected, Buffer.from(received, "hex"))) {
85
+ throw new ZenAuthWebhookError("Webhook signature does not match");
86
+ }
87
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > (input.toleranceSec ?? 300)) {
88
+ throw new ZenAuthWebhookError("Webhook signature is too old");
89
+ }
90
+ return JSON.parse(body);
91
+ }
92
+ export {
93
+ ZenAuthTokenError,
94
+ ZenAuthWebhookError,
95
+ createZenAuth,
96
+ getBearerToken,
97
+ verifyWebhook
98
+ };
99
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\nimport { createRemoteJWKSet, errors as joseErrors, jwtVerify, type JWTVerifyGetKey } from \"jose\";\n\nexport interface ZenAuthVerifierOptions {\n /** Base URL of the ZenAuth API, e.g. `https://api.zenauth.example.com`. Must match the token `iss`. */\n issuer: string;\n /**\n * Your application's client ID. When set, tokens issued to any other application are rejected.\n * Strongly recommended: without it, a token minted for a different app would be accepted.\n */\n clientId?: string;\n /** Allowed clock drift in seconds when checking `exp` / `nbf`. Default 5. */\n clockToleranceSec?: number;\n /** Advanced: custom key resolver (used by tests). Defaults to the issuer's JWKS endpoint. */\n keys?: JWTVerifyGetKey;\n}\n\nexport interface Organization {\n id: string;\n slug: string;\n name: string;\n role: \"owner\" | \"admin\" | \"member\";\n}\n\nexport interface VerifiedToken {\n /** The user's role in your app, if one applies. */\n role?: string;\n /** The user's teams. Present when the `organizations` scope was granted. */\n orgs?: Organization[];\n /** ZenAuth user id. Stable: use it as the foreign key to your own user row. */\n userId: string;\n /** Client ID the token was issued to. */\n clientId: string;\n /** Granted scopes, e.g. `[\"openid\", \"profile\", \"email\"]`. */\n scopes: string[];\n /** Expiry as a Unix timestamp (seconds). */\n expiresAt: number;\n /** All claims in the token. */\n claims: Record<string, unknown>;\n}\n\nexport interface UserInfo {\n sub: string;\n /** Present when the `profile` scope was granted. */\n name?: string;\n /** Present when the `email` scope was granted. */\n email?: string;\n email_verified?: boolean;\n role?: string;\n orgs?: Organization[];\n}\n\nexport type TokenErrorCode =\n | \"missing_token\"\n | \"invalid_token\"\n | \"token_expired\"\n | \"wrong_client\"\n | \"userinfo_failed\";\n\nexport class ZenAuthTokenError extends Error {\n readonly code: TokenErrorCode;\n constructor(code: TokenErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"ZenAuthTokenError\";\n this.code = code;\n }\n}\n\nconst stripTrailingSlash = (url: string) => url.replace(/\\/+$/, \"\");\n\n/**\n * Extracts the token from an `Authorization: Bearer <token>` header value.\n * Returns `null` if the header is absent or not a Bearer credential.\n */\nexport function getBearerToken(authorizationHeader: string | null | undefined): string | null {\n if (!authorizationHeader) return null;\n const match = /^Bearer\\s+(\\S+)$/i.exec(authorizationHeader.trim());\n return match?.[1] ?? null;\n}\n\n/**\n * Creates a reusable verifier. Create it ONCE at startup: it caches the issuer's public keys\n * (and refreshes them automatically when ZenAuth rotates its signing key).\n *\n * ```ts\n * const zenauth = createZenAuth({ issuer: process.env.ZENAUTH_ISSUER!, clientId: process.env.ZENAUTH_CLIENT_ID! });\n * const { userId } = await zenauth.verifyToken(getBearerToken(req.headers.authorization));\n * ```\n */\nexport function createZenAuth(options: ZenAuthVerifierOptions) {\n const issuer = stripTrailingSlash(options.issuer);\n const keys = options.keys ?? createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`));\n\n /**\n * Verifies signature (RS256 only), issuer and expiry, and that the token was issued to your app.\n * Throws {@link ZenAuthTokenError} on any failure. Never trusts an unverified token.\n */\n async function verifyToken(token: string | null | undefined): Promise<VerifiedToken> {\n if (!token) throw new ZenAuthTokenError(\"missing_token\", \"No access token provided\");\n\n let claims: Record<string, unknown>;\n try {\n const { payload } = await jwtVerify(token, keys, {\n issuer,\n algorithms: [\"RS256\"],\n clockTolerance: options.clockToleranceSec ?? 5,\n });\n claims = payload as Record<string, unknown>;\n } catch (err) {\n if (err instanceof joseErrors.JWTExpired) {\n throw new ZenAuthTokenError(\"token_expired\", \"Access token has expired\", { cause: err });\n }\n throw new ZenAuthTokenError(\"invalid_token\", \"Access token is invalid\", { cause: err });\n }\n\n const sub = typeof claims.sub === \"string\" ? claims.sub : \"\";\n // Access tokens carry `client_id`; ID tokens carry `aud`. Accept either.\n const aud = Array.isArray(claims.aud) ? claims.aud[0] : claims.aud;\n const tokenClient =\n typeof claims.client_id === \"string\" ? claims.client_id : typeof aud === \"string\" ? aud : \"\";\n\n if (!sub || !tokenClient) {\n throw new ZenAuthTokenError(\"invalid_token\", \"Token is missing required claims\");\n }\n if (options.clientId && tokenClient !== options.clientId) {\n throw new ZenAuthTokenError(\"wrong_client\", \"Token was not issued to this application\");\n }\n\n return {\n userId: sub,\n clientId: tokenClient,\n ...(typeof claims.role === \"string\" && { role: claims.role }),\n ...(Array.isArray(claims.orgs) && { orgs: claims.orgs as Organization[] }),\n scopes: typeof claims.scope === \"string\" ? claims.scope.split(\" \").filter(Boolean) : [],\n expiresAt: typeof claims.exp === \"number\" ? claims.exp : 0,\n claims,\n };\n }\n\n /**\n * Fetches the user's profile (name, email, email_verified) from ZenAuth.\n * Access tokens only carry the user id, so call this once when you first create your local user row.\n */\n async function getUserInfo(accessToken: string): Promise<UserInfo> {\n await verifyToken(accessToken);\n let res: Response;\n try {\n res = await fetch(`${issuer}/o/userinfo`, { headers: { authorization: `Bearer ${accessToken}` } });\n } catch (err) {\n throw new ZenAuthTokenError(\"userinfo_failed\", \"Could not reach ZenAuth\", { cause: err });\n }\n if (!res.ok) {\n throw new ZenAuthTokenError(\"userinfo_failed\", `ZenAuth userinfo returned ${res.status}`);\n }\n return (await res.json()) as UserInfo;\n }\n\n return { verifyToken, getUserInfo, issuer };\n}\n\nexport type ZenAuth = ReturnType<typeof createZenAuth>;\n\n// ── Webhooks ────────────────────────────────────────────────\nexport interface WebhookEvent {\n /** Unique per delivery attempt group: store it to ignore retries you already handled. */\n id: string;\n type: \"user.created\" | \"user.login\" | \"user.deleted\" | \"ping\";\n client_id: string;\n created_at: string;\n data: Record<string, unknown>;\n}\n\nexport class ZenAuthWebhookError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ZenAuthWebhookError\";\n }\n}\n\n/**\n * Checks the `ZenAuth-Signature` header and returns the event. Pass the RAW request body: re-serialised\n * JSON does not match the signature.\n *\n * ```ts\n * app.post(\"/webhooks/zenauth\", express.raw({ type: \"application/json\" }), (req, res) => {\n * const event = verifyWebhook({ payload: req.body, signature: req.get(\"zenauth-signature\"), secret });\n * res.sendStatus(200);\n * });\n * ```\n */\nexport function verifyWebhook(input: {\n payload: string | Uint8Array;\n signature: string | null | undefined;\n secret: string;\n /** Oldest accepted signature, to stop replays. Default 300 seconds. */\n toleranceSec?: number;\n}): WebhookEvent {\n const body = typeof input.payload === \"string\" ? input.payload : Buffer.from(input.payload).toString(\"utf8\");\n const match = /^t=(\\d+),v1=([0-9a-f]{64})$/.exec(input.signature ?? \"\");\n if (!match) throw new ZenAuthWebhookError(\"Missing or malformed ZenAuth-Signature header\");\n const [, timestamp, received] = match as unknown as [string, string, string];\n\n if (!input.secret) throw new ZenAuthWebhookError(\"Webhook secret is not configured\");\n const expected = createHmac(\"sha256\", input.secret).update(`${timestamp}.${body}`).digest();\n if (!timingSafeEqual(expected, Buffer.from(received, \"hex\"))) {\n throw new ZenAuthWebhookError(\"Webhook signature does not match\");\n }\n if (Math.abs(Date.now() / 1000 - Number(timestamp)) > (input.toleranceSec ?? 300)) {\n throw new ZenAuthWebhookError(\"Webhook signature is too old\");\n }\n return JSON.parse(body) as WebhookEvent;\n}\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAC5C,SAAS,oBAAoB,UAAU,YAAY,iBAAuC;AA0DnF,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAClC;AAAA,EACT,YAAY,MAAsB,SAAiB,SAA+B;AAChF,UAAM,SAAS,OAAO;AACtB,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,qBAAqB,CAAC,QAAgB,IAAI,QAAQ,QAAQ,EAAE;AAM3D,SAAS,eAAe,qBAA+D;AAC5F,MAAI,CAAC,oBAAqB,QAAO;AACjC,QAAM,QAAQ,oBAAoB,KAAK,oBAAoB,KAAK,CAAC;AACjE,SAAO,QAAQ,CAAC,KAAK;AACvB;AAWO,SAAS,cAAc,SAAiC;AAC7D,QAAM,SAAS,mBAAmB,QAAQ,MAAM;AAChD,QAAM,OAAO,QAAQ,QAAQ,mBAAmB,IAAI,IAAI,GAAG,MAAM,wBAAwB,CAAC;AAM1F,iBAAe,YAAY,OAA0D;AACnF,QAAI,CAAC,MAAO,OAAM,IAAI,kBAAkB,iBAAiB,0BAA0B;AAEnF,QAAI;AACJ,QAAI;AACF,YAAM,EAAE,QAAQ,IAAI,MAAM,UAAU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"name": "@zenauth/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Server-side helpers for ZenAuth: verify access tokens against your ZenAuth JWKS and look up the signed-in user.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "zenauth",
8
+ "auth",
9
+ "openid-connect",
10
+ "oidc",
11
+ "jwt",
12
+ "jwks",
13
+ "authentication"
14
+ ],
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "main": "./dist/index.cjs",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "import": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/index.d.cts",
28
+ "default": "./dist/index.cjs"
29
+ }
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "dependencies": {
44
+ "jose": "^6.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.15.3",
48
+ "tsup": "^8.5.1",
49
+ "tsx": "^4.21.0",
50
+ "typescript": "^5.9.3",
51
+ "@repo/typescript-config": "0.0.0"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "check-types": "tsc --noEmit",
56
+ "test": "tsx --test \"src/**/*.test.ts\""
57
+ }
6
58
  }