@tillstack/auth-node 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/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @tillstack/auth-node
2
+
3
+ Server-side [TillAuth](https://tilldev.dev) SDK for Node.js — verify TillAuth
4
+ JWTs and protect your routes. Verification is offline against a cached JWKS
5
+ (EdDSA), so there is no round-trip to TillAuth on the hot path.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @tillstack/auth-node
11
+ # or: pnpm add @tillstack/auth-node
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ import { createVerifier } from '@tillstack/auth-node'
18
+
19
+ const verifier = createVerifier({
20
+ appId: 'tau_your_app_id', // TillAuth public app id
21
+ // apiBase: 'https://auth.tilldev.dev', // default
22
+ // requireMfa: true,
23
+ })
24
+
25
+ // Verify a raw token, or pull it straight from an Authorization header:
26
+ const claims = await verifier.verifyHeader(req.headers.authorization)
27
+ // claims.sub, claims.email, claims.mfa, claims.exp
28
+ ```
29
+
30
+ ### Express
31
+
32
+ ```ts
33
+ import express from 'express'
34
+ import { createVerifier, expressMiddleware } from '@tillstack/auth-node'
35
+
36
+ const app = express()
37
+ const verifier = createVerifier({ appId: 'tau_your_app_id' })
38
+
39
+ app.use(expressMiddleware(verifier)) // sets req.user to the verified claims
40
+ ```
41
+
42
+ ### Fastify
43
+
44
+ ```ts
45
+ import { createVerifier, fastifyHook } from '@tillstack/auth-node'
46
+
47
+ const verifier = createVerifier({ appId: 'tau_your_app_id' })
48
+ fastify.addHook('preHandler', fastifyHook(verifier)) // sets req.user
49
+ ```
50
+
51
+ For fully air-gapped verification, pass inline public keys via `publicJwks`
52
+ instead of letting the SDK fetch the JWKS.
53
+
54
+ ## Docs
55
+
56
+ Full documentation: https://tilldev.dev/docs
57
+
58
+ ## License
59
+
60
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,269 @@
1
+ 'use strict';
2
+
3
+ var jose = require('jose');
4
+
5
+ // src/index.ts
6
+
7
+ // src/cookie-proxy.ts
8
+ var DEFAULT_API = "https://auth.tilldev.dev";
9
+ function resolve(opts) {
10
+ return {
11
+ appId: opts.appId,
12
+ apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\/$/, ""),
13
+ accessCookie: opts.accessCookie ?? "tau_at",
14
+ refreshCookie: opts.refreshCookie ?? "tau_rt",
15
+ cookiePath: opts.cookiePath ?? "/",
16
+ cookieDomain: opts.cookieDomain ?? "",
17
+ secure: opts.secure ?? process.env.NODE_ENV === "production"
18
+ };
19
+ }
20
+ function makeCookie(name, value, o, opts = {}) {
21
+ const parts = [`${name}=${opts.clear ? "" : value}`];
22
+ parts.push("HttpOnly");
23
+ if (o.secure) parts.push("Secure");
24
+ parts.push("SameSite=Lax");
25
+ parts.push(`Path=${o.cookiePath}`);
26
+ if (o.cookieDomain) parts.push(`Domain=${o.cookieDomain}`);
27
+ if (opts.clear) parts.push("Max-Age=0");
28
+ else if (opts.maxAge !== void 0) parts.push(`Max-Age=${opts.maxAge}`);
29
+ return parts.join("; ");
30
+ }
31
+ async function handleProxy(req, raw) {
32
+ const opts = resolve(raw);
33
+ const path = req.pathname.replace(/^\/+/, "");
34
+ const url = `${opts.apiBase}/v1/${path}`;
35
+ const headers = {
36
+ "Content-Type": "application/json",
37
+ "X-TillAuth-App": opts.appId,
38
+ "User-Agent": "tilldev-auth-node/cookie-proxy"
39
+ };
40
+ let body = req.body;
41
+ if (path === "me" && req.cookies[opts.accessCookie]) {
42
+ headers.Authorization = `Bearer ${req.cookies[opts.accessCookie]}`;
43
+ }
44
+ if (path === "refresh") {
45
+ const rt = req.cookies[opts.refreshCookie];
46
+ if (!rt) {
47
+ return {
48
+ status: 401,
49
+ body: JSON.stringify({ error: "no refresh cookie" }),
50
+ setCookies: [],
51
+ headers: { "Content-Type": "application/json" }
52
+ };
53
+ }
54
+ body = JSON.stringify({ refresh_token: rt });
55
+ }
56
+ if (path === "signout") {
57
+ const rt = req.cookies[opts.refreshCookie];
58
+ body = JSON.stringify({ refresh_token: rt ?? "" });
59
+ }
60
+ const upstream = await fetch(url, { method: req.method, headers, body });
61
+ const text = await upstream.text();
62
+ let json = {};
63
+ try {
64
+ json = JSON.parse(text);
65
+ } catch {
66
+ json = {};
67
+ }
68
+ const setCookies = [];
69
+ const out = { ...json };
70
+ if (typeof json.access_token === "string") {
71
+ setCookies.push(makeCookie(opts.accessCookie, json.access_token, opts, { maxAge: 60 * 10 }));
72
+ delete out.access_token;
73
+ }
74
+ if (typeof json.refresh_token === "string") {
75
+ setCookies.push(makeCookie(opts.refreshCookie, json.refresh_token, opts, { maxAge: 60 * 60 * 24 * 30 }));
76
+ delete out.refresh_token;
77
+ delete out.refresh_expires_at;
78
+ }
79
+ if (path === "signout") {
80
+ setCookies.push(makeCookie(opts.accessCookie, "", opts, { clear: true }));
81
+ setCookies.push(makeCookie(opts.refreshCookie, "", opts, { clear: true }));
82
+ }
83
+ return {
84
+ status: upstream.status,
85
+ body: JSON.stringify(out),
86
+ setCookies,
87
+ headers: { "Content-Type": "application/json" }
88
+ };
89
+ }
90
+ function createFetchHandler(opts) {
91
+ return async function handler(req, ctx = {}) {
92
+ const url = new URL(req.url);
93
+ let pathname;
94
+ if (ctx.params?.path) {
95
+ pathname = Array.isArray(ctx.params.path) ? `/${ctx.params.path.join("/")}` : `/${ctx.params.path}`;
96
+ } else {
97
+ pathname = url.pathname.replace(/^\/api\/auth/, "");
98
+ }
99
+ const cookies = parseCookieHeader(req.headers.get("cookie"));
100
+ const body = req.method === "POST" ? await req.text() : "{}";
101
+ const out = await handleProxy({ method: req.method, pathname, body, cookies }, opts);
102
+ const headers = new Headers(out.headers);
103
+ for (const c of out.setCookies) headers.append("Set-Cookie", c);
104
+ return new Response(out.body, { status: out.status, headers });
105
+ };
106
+ }
107
+ function expressCookieProxy(opts) {
108
+ return async function(req, res) {
109
+ const path = req.path ?? (req.originalUrl ?? req.url ?? "/").replace(/^\/api\/auth/, "").split("?")[0] ?? "/";
110
+ const cookieHeader = typeof req.headers.cookie === "string" ? req.headers.cookie : Array.isArray(req.headers.cookie) ? req.headers.cookie[0] : "";
111
+ const body = typeof req.body === "string" ? req.body : req.body ? JSON.stringify(req.body) : "{}";
112
+ const out = await handleProxy(
113
+ {
114
+ method: req.method,
115
+ pathname: path,
116
+ body,
117
+ cookies: parseCookieHeader(cookieHeader ?? null)
118
+ },
119
+ opts
120
+ );
121
+ res.status(out.status);
122
+ if (out.setCookies.length > 0) res.setHeader("Set-Cookie", out.setCookies);
123
+ for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v);
124
+ res.json(JSON.parse(out.body));
125
+ };
126
+ }
127
+ function parseCookieHeader(header) {
128
+ const out = {};
129
+ if (!header) return out;
130
+ for (const part of header.split(";")) {
131
+ const [k, ...rest] = part.trim().split("=");
132
+ if (!k) continue;
133
+ out[k] = decodeURIComponent(rest.join("="));
134
+ }
135
+ return out;
136
+ }
137
+
138
+ // src/index.ts
139
+ var DEFAULT_API2 = "https://auth.tilldev.dev";
140
+ var ISSUER = "tillauth";
141
+ var TillAuthVerifyError = class extends Error {
142
+ constructor(message, code) {
143
+ super(message);
144
+ this.name = "TillAuthVerifyError";
145
+ this.code = code;
146
+ }
147
+ };
148
+ var TillAuthVerifier = class {
149
+ constructor(opts) {
150
+ if (!opts.appId) throw new Error("TillAuthVerifier: appId is required");
151
+ this.opts = {
152
+ appId: opts.appId,
153
+ apiBase: (opts.apiBase ?? DEFAULT_API2).replace(/\/$/, ""),
154
+ requireVerifiedEmail: opts.requireVerifiedEmail ?? false,
155
+ requireMfa: opts.requireMfa ?? false
156
+ };
157
+ if (opts.publicJwks && opts.publicJwks.length > 0) {
158
+ this.remote = null;
159
+ this.inlineKeys = Promise.all(
160
+ opts.publicJwks.map(async (k) => ({ kid: k.kid, key: await jose.importJWK(k, "EdDSA") }))
161
+ );
162
+ } else {
163
+ this.remote = jose.createRemoteJWKSet(new URL(`${this.opts.apiBase}/.well-known/jwks.json`));
164
+ this.inlineKeys = null;
165
+ }
166
+ }
167
+ async verify(token) {
168
+ if (!token) throw new TillAuthVerifyError("No token", "no_token");
169
+ let claims;
170
+ try {
171
+ if (this.inlineKeys) {
172
+ const keys = await this.inlineKeys;
173
+ let lastErr;
174
+ for (const k of keys) {
175
+ try {
176
+ const { payload: payload2 } = await jose.jwtVerify(token, k.key, {
177
+ algorithms: ["EdDSA"],
178
+ issuer: ISSUER
179
+ });
180
+ claims = payload2;
181
+ return this.applyClaimsChecks(claims);
182
+ } catch (e) {
183
+ lastErr = e;
184
+ }
185
+ }
186
+ throw lastErr ?? new Error("No key matched");
187
+ }
188
+ const { payload } = await jose.jwtVerify(token, this.remote, {
189
+ algorithms: ["EdDSA"],
190
+ issuer: ISSUER
191
+ });
192
+ claims = payload;
193
+ } catch (e) {
194
+ throw new TillAuthVerifyError(
195
+ e instanceof Error ? e.message : "Invalid token",
196
+ "invalid_token"
197
+ );
198
+ }
199
+ return this.applyClaimsChecks(claims);
200
+ }
201
+ applyClaimsChecks(claims) {
202
+ if (claims.app !== this.opts.appId) {
203
+ throw new TillAuthVerifyError(`Token issued for different app`, "wrong_app");
204
+ }
205
+ if (this.opts.requireMfa && !claims.mfa) {
206
+ throw new TillAuthVerifyError("MFA required", "mfa_required");
207
+ }
208
+ if (this.opts.requireVerifiedEmail && claims.email_verified !== true) {
209
+ throw new TillAuthVerifyError("Email not verified", "email_not_verified");
210
+ }
211
+ return claims;
212
+ }
213
+ /**
214
+ * Pull a Bearer token out of an Authorization header and verify. Returns
215
+ * the claims or throws TillAuthVerifyError.
216
+ */
217
+ async verifyHeader(authHeader) {
218
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
219
+ throw new TillAuthVerifyError("Missing Bearer token", "no_token");
220
+ }
221
+ return this.verify(authHeader.slice(7));
222
+ }
223
+ };
224
+ function expressMiddleware(verifier, opts = {}) {
225
+ return async function(req, res, next) {
226
+ try {
227
+ const h = req.headers?.authorization;
228
+ const claims = await verifier.verifyHeader(Array.isArray(h) ? h[0] : h);
229
+ req.user = claims;
230
+ next();
231
+ } catch (e) {
232
+ const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError("Auth failed", "invalid_token");
233
+ if (opts.onError) {
234
+ const out = opts.onError(err);
235
+ if (out !== void 0) {
236
+ res.status(401).json(out);
237
+ return;
238
+ }
239
+ }
240
+ res.status(401).json({ error: err.message, code: err.code });
241
+ }
242
+ };
243
+ }
244
+ function fastifyHook(verifier) {
245
+ return async function(req, reply) {
246
+ try {
247
+ const h = req.headers["authorization"];
248
+ const auth = Array.isArray(h) ? h[0] : h;
249
+ const claims = await verifier.verifyHeader(auth);
250
+ req.user = claims;
251
+ } catch (e) {
252
+ const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError("Auth failed", "invalid_token");
253
+ reply.code(401).send({ error: err.message, code: err.code });
254
+ }
255
+ };
256
+ }
257
+ function createVerifier(opts) {
258
+ return new TillAuthVerifier(opts);
259
+ }
260
+
261
+ exports.TillAuthVerifier = TillAuthVerifier;
262
+ exports.TillAuthVerifyError = TillAuthVerifyError;
263
+ exports.createFetchHandler = createFetchHandler;
264
+ exports.createVerifier = createVerifier;
265
+ exports.expressCookieProxy = expressCookieProxy;
266
+ exports.expressMiddleware = expressMiddleware;
267
+ exports.fastifyHook = fastifyHook;
268
+ //# sourceMappingURL=index.cjs.map
269
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cookie-proxy.ts","../src/index.ts"],"names":["DEFAULT_API","importJWK","createRemoteJWKSet","payload","jwtVerify"],"mappings":";;;;;;;AAWA,IAAM,WAAA,GAAc,0BAAA;AAuCpB,SAAS,QAAQ,IAAA,EAAwD;AACvE,EAAA,OAAO;AAAA,IACL,OAAO,IAAA,CAAK,KAAA;AAAA,IACZ,UAAU,IAAA,CAAK,OAAA,IAAW,WAAA,EAAa,OAAA,CAAQ,OAAO,EAAE,CAAA;AAAA,IACxD,Y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AAE,IAAA,CAAK,GAA8B,CAAA;AACnD,UAAA;AAAA,QACF;AAAA,MACF;AACA,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,OAAA,EAAS,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,CAAA;AAAA,IAC7D;AAAA,EACF,CAAA;AACF;AAUO,SAAS,YAAY,QAAA,EAA4B;AACtD,EAAA,OAAO,eACL,KACA,KAAA,EACA;AACA,IAAA,IAAI;AACF,MAAA,MAAM,CAAA,GAAI,GAAA,CAAI,OAAA,CAAQ,eAAe,CAAA;AACrC,MAAA,MAAM,OAAO,KAAA,CAAM,OAAA,CAAQ,CAAC,CAAA,GAAI,CAAA,CAAE,CAAC,CAAA,GAAI,CAAA;AACvC,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,YAAA,CAAa,IAAI,CAAA;AAC/C,MAAA,GAAA,CAAI,IAAA,GAAO,MAAA;AAAA,IACb,SAAS,CAAA,EAAG;AACV,MAAA,MAAM,MAAM,CAAA,YAAa,mBAAA,GAAsB,IAAI,IAAI,mBAAA,CAAoB,eAAe,eAAe,CAAA;AACzG,MAAA,KAAA,CAAM,IAAA,CAAK,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,GAAA,CAAI,OAAA,EAAS,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,CAAA;AAAA,IAC7D;AAAA,EACF,CAAA;AACF;AAGO,SAAS,eAAe,IAAA,EAAuC;AACpE,EAAA,OAAO,IAAI,iBAAiB,IAAI,CAAA;AAClC","file":"index.cjs","sourcesContent":["// Cookie-mode proxy for TillAuth.\n//\n// Mount this on the customer's backend (typically at /api/auth/*). It\n// forwards JSON bodies to TillAuth's /v1/* endpoints, then translates\n// access_token + refresh_token in the response into HttpOnly cookies on\n// the customer's domain. The browser's localStorage never sees the\n// tokens — XSS can't exfiltrate them.\n//\n// Two adapters: a generic web-fetch handler (Cloudflare Workers, Next.js\n// Route Handlers, Bun, Deno) and an Express middleware. Pick one.\n\nconst DEFAULT_API = 'https://auth.tilldev.dev'\n\nexport interface CookieProxyOptions {\n /** TillAuth public app id (`tau_…`). */\n appId: string\n /** Override the TillAuth API base. */\n apiBase?: string\n /** Cookie name for the access token. Default `tau_at`. */\n accessCookie?: string\n /** Cookie name for the refresh token. Default `tau_rt`. */\n refreshCookie?: string\n /** Cookie path. Default '/'. */\n cookiePath?: string\n /** Cookie domain (e.g. `.example.com` to share across subdomains). */\n cookieDomain?: string\n /** Secure flag. Defaults to true in production, false otherwise. */\n secure?: boolean\n}\n\ninterface NormalizedRequest {\n method: string\n pathname: string // path relative to the mount point (`/signin`, `/refresh`)\n body: string\n cookies: Record<string, string>\n}\ninterface NormalizedResponse {\n status: number\n body: string\n setCookies: string[]\n headers: Record<string, string>\n}\n\ninterface AuthBody {\n access_token?: string\n refresh_token?: string\n refresh_expires_at?: string\n [key: string]: unknown\n}\n\nfunction resolve(opts: CookieProxyOptions): Required<CookieProxyOptions> {\n return {\n appId: opts.appId,\n apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\\/$/, ''),\n accessCookie: opts.accessCookie ?? 'tau_at',\n refreshCookie: opts.refreshCookie ?? 'tau_rt',\n cookiePath: opts.cookiePath ?? '/',\n cookieDomain: opts.cookieDomain ?? '',\n secure: opts.secure ?? process.env.NODE_ENV === 'production',\n }\n}\n\nfunction makeCookie(\n name: string,\n value: string,\n o: Required<CookieProxyOptions>,\n opts: { maxAge?: number; clear?: boolean } = {},\n): string {\n const parts = [`${name}=${opts.clear ? '' : value}`]\n parts.push('HttpOnly')\n if (o.secure) parts.push('Secure')\n parts.push('SameSite=Lax')\n parts.push(`Path=${o.cookiePath}`)\n if (o.cookieDomain) parts.push(`Domain=${o.cookieDomain}`)\n if (opts.clear) parts.push('Max-Age=0')\n else if (opts.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`)\n return parts.join('; ')\n}\n\nasync function handleProxy(req: NormalizedRequest, raw: CookieProxyOptions): Promise<NormalizedResponse> {\n const opts = resolve(raw)\n const path = req.pathname.replace(/^\\/+/, '')\n\n // Map proxy paths → TillAuth paths.\n const url = `${opts.apiBase}/v1/${path}`\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-TillAuth-App': opts.appId,\n 'User-Agent': 'tilldev-auth-node/cookie-proxy',\n }\n\n // /me, /refresh, /signout need to carry tokens from cookies, not the body.\n let body = req.body\n if (path === 'me' && req.cookies[opts.accessCookie]) {\n headers.Authorization = `Bearer ${req.cookies[opts.accessCookie]}`\n }\n if (path === 'refresh') {\n const rt = req.cookies[opts.refreshCookie]\n if (!rt) {\n return {\n status: 401,\n body: JSON.stringify({ error: 'no refresh cookie' }),\n setCookies: [],\n headers: { 'Content-Type': 'application/json' },\n }\n }\n body = JSON.stringify({ refresh_token: rt })\n }\n if (path === 'signout') {\n const rt = req.cookies[opts.refreshCookie]\n body = JSON.stringify({ refresh_token: rt ?? '' })\n }\n\n const upstream = await fetch(url, { method: req.method, headers, body })\n const text = await upstream.text()\n let json: AuthBody = {}\n try {\n json = JSON.parse(text) as AuthBody\n } catch {\n json = {}\n }\n\n const setCookies: string[] = []\n // Always strip token fields before returning to the SPA.\n const out = { ...json }\n\n if (typeof json.access_token === 'string') {\n setCookies.push(makeCookie(opts.accessCookie, json.access_token, opts, { maxAge: 60 * 10 }))\n delete out.access_token\n }\n if (typeof json.refresh_token === 'string') {\n // 30d in line with the Fastify REFRESH_TTL_MS.\n setCookies.push(makeCookie(opts.refreshCookie, json.refresh_token, opts, { maxAge: 60 * 60 * 24 * 30 }))\n delete out.refresh_token\n delete out.refresh_expires_at\n }\n if (path === 'signout') {\n setCookies.push(makeCookie(opts.accessCookie, '', opts, { clear: true }))\n setCookies.push(makeCookie(opts.refreshCookie, '', opts, { clear: true }))\n }\n\n return {\n status: upstream.status,\n body: JSON.stringify(out),\n setCookies,\n headers: { 'Content-Type': 'application/json' },\n }\n}\n\n// ── Adapter 1: web-fetch (Next.js Route Handlers, Workers, Bun, Deno) ───────\n\nexport function createFetchHandler(opts: CookieProxyOptions) {\n return async function handler(req: Request, ctx: { params?: { path?: string | string[] } } = {}): Promise<Response> {\n const url = new URL(req.url)\n // Derive the proxy-relative path. Prefer ctx.params.path (Next.js catch-all);\n // fall back to the part of the URL after the mount point heuristic.\n let pathname: string\n if (ctx.params?.path) {\n pathname = Array.isArray(ctx.params.path) ? `/${ctx.params.path.join('/')}` : `/${ctx.params.path}`\n } else {\n pathname = url.pathname.replace(/^\\/api\\/auth/, '')\n }\n const cookies = parseCookieHeader(req.headers.get('cookie'))\n const body = req.method === 'POST' ? await req.text() : '{}'\n const out = await handleProxy({ method: req.method, pathname, body, cookies }, opts)\n const headers = new Headers(out.headers)\n for (const c of out.setCookies) headers.append('Set-Cookie', c)\n return new Response(out.body, { status: out.status, headers })\n }\n}\n\n// ── Adapter 2: Express ──────────────────────────────────────────────────────\n\ninterface ExpReq {\n method: string\n url?: string\n originalUrl?: string\n path?: string\n body?: unknown\n headers: Record<string, string | string[] | undefined>\n}\ninterface ExpRes {\n status(n: number): ExpRes\n setHeader(name: string, value: string | string[]): void\n json(body: unknown): void\n}\n\nexport function expressCookieProxy(opts: CookieProxyOptions) {\n return async function (req: ExpReq, res: ExpRes): Promise<void> {\n const path =\n req.path ?? (req.originalUrl ?? req.url ?? '/').replace(/^\\/api\\/auth/, '').split('?')[0] ?? '/'\n const cookieHeader =\n typeof req.headers.cookie === 'string' ? req.headers.cookie : Array.isArray(req.headers.cookie) ? req.headers.cookie[0] : ''\n const body =\n typeof req.body === 'string' ? req.body : req.body ? JSON.stringify(req.body) : '{}'\n const out = await handleProxy(\n {\n method: req.method,\n pathname: path,\n body,\n cookies: parseCookieHeader(cookieHeader ?? null),\n },\n opts,\n )\n res.status(out.status)\n if (out.setCookies.length > 0) res.setHeader('Set-Cookie', out.setCookies)\n for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v)\n res.json(JSON.parse(out.body))\n }\n}\n\nfunction parseCookieHeader(header: string | null): Record<string, string> {\n const out: Record<string, string> = {}\n if (!header) return out\n for (const part of header.split(';')) {\n const [k, ...rest] = part.trim().split('=')\n if (!k) continue\n out[k] = decodeURIComponent(rest.join('='))\n }\n return out\n}\n","import { jwtVerify, createRemoteJWKSet, importJWK, type JWK } from 'jose'\n\n// Server-side TillAuth verification.\n//\n// You configure once with the issuer + JWKS endpoint (or inline public keys),\n// then call `verify(token)` or use the framework-specific middleware.\n//\n// Verification is offline against the cached JWKS — no round-trip to TillAuth\n// on the hot path.\n\nconst DEFAULT_API = 'https://auth.tilldev.dev'\nconst ISSUER = 'tillauth'\n\nexport interface VerifyOptions {\n /** TillAuth public app id (`tau_…`). Used to enforce app scoping. */\n appId: string\n /** TillAuth API base. Defaults to https://auth.tilldev.dev */\n apiBase?: string\n /**\n * Inline JWKS as a JWK array (the same `publicJwk` entries you'd find in\n * the TILLAUTH_JWT_KEYS env). Use this in environments where you want\n * fully air-gapped verification.\n */\n publicJwks?: JWK[]\n /** Require email_verified=true. Defaults to false. */\n requireVerifiedEmail?: boolean\n /** Require MFA was satisfied this session. Defaults to false. */\n requireMfa?: boolean\n}\n\nexport interface AuthClaims {\n /** User id */\n sub: string\n /** App id the token was issued for */\n app: string\n /** Lowercased email */\n email: string\n /** Whether MFA was satisfied this session */\n mfa: boolean\n /**\n * Whether the account's email was verified at issue time. Optional: tokens\n * minted before this claim existed omit it. When `requireVerifiedEmail` is\n * set, an absent claim is treated as unverified (fail-closed on the check).\n */\n email_verified?: boolean\n /** Issued-at (seconds) */\n iat: number\n /** Expires-at (seconds) */\n exp: number\n}\n\nexport class TillAuthVerifyError extends Error {\n code: 'no_token' | 'invalid_token' | 'wrong_app' | 'mfa_required' | 'email_not_verified'\n constructor(message: string, code: TillAuthVerifyError['code']) {\n super(message)\n this.name = 'TillAuthVerifyError'\n this.code = code\n }\n}\n\nexport class TillAuthVerifier {\n private readonly opts: Required<Pick<VerifyOptions, 'appId' | 'apiBase' | 'requireVerifiedEmail' | 'requireMfa'>>\n private readonly remote: ReturnType<typeof createRemoteJWKSet> | null\n private readonly inlineKeys: Promise<Array<{ kid?: string; key: Awaited<ReturnType<typeof importJWK>> }>> | null\n\n constructor(opts: VerifyOptions) {\n if (!opts.appId) throw new Error('TillAuthVerifier: appId is required')\n this.opts = {\n appId: opts.appId,\n apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\\/$/, ''),\n requireVerifiedEmail: opts.requireVerifiedEmail ?? false,\n requireMfa: opts.requireMfa ?? false,\n }\n if (opts.publicJwks && opts.publicJwks.length > 0) {\n this.remote = null\n this.inlineKeys = Promise.all(\n opts.publicJwks.map(async (k) => ({ kid: k.kid, key: await importJWK(k, 'EdDSA') })),\n )\n } else {\n this.remote = createRemoteJWKSet(new URL(`${this.opts.apiBase}/.well-known/jwks.json`))\n this.inlineKeys = null\n }\n }\n\n async verify(token: string): Promise<AuthClaims> {\n if (!token) throw new TillAuthVerifyError('No token', 'no_token')\n\n let claims: AuthClaims\n try {\n if (this.inlineKeys) {\n const keys = await this.inlineKeys\n let lastErr: unknown\n for (const k of keys) {\n try {\n const { payload } = await jwtVerify(token, k.key, {\n algorithms: ['EdDSA'],\n issuer: ISSUER,\n })\n claims = payload as unknown as AuthClaims\n return this.applyClaimsChecks(claims)\n } catch (e) {\n lastErr = e\n }\n }\n throw lastErr ?? new Error('No key matched')\n }\n const { payload } = await jwtVerify(token, this.remote!, {\n algorithms: ['EdDSA'],\n issuer: ISSUER,\n })\n claims = payload as unknown as AuthClaims\n } catch (e) {\n throw new TillAuthVerifyError(\n e instanceof Error ? e.message : 'Invalid token',\n 'invalid_token',\n )\n }\n return this.applyClaimsChecks(claims)\n }\n\n private applyClaimsChecks(claims: AuthClaims): AuthClaims {\n if (claims.app !== this.opts.appId) {\n throw new TillAuthVerifyError(`Token issued for different app`, 'wrong_app')\n }\n if (this.opts.requireMfa && !claims.mfa) {\n throw new TillAuthVerifyError('MFA required', 'mfa_required')\n }\n // Absent claim (older tokens) is treated as unverified only when the check\n // is enabled — so requireVerifiedEmail fails closed rather than silently\n // passing when the issuer predates the claim.\n if (this.opts.requireVerifiedEmail && claims.email_verified !== true) {\n throw new TillAuthVerifyError('Email not verified', 'email_not_verified')\n }\n return claims\n }\n\n /**\n * Pull a Bearer token out of an Authorization header and verify. Returns\n * the claims or throws TillAuthVerifyError.\n */\n async verifyHeader(authHeader: string | undefined | null): Promise<AuthClaims> {\n if (!authHeader || !authHeader.startsWith('Bearer ')) {\n throw new TillAuthVerifyError('Missing Bearer token', 'no_token')\n }\n return this.verify(authHeader.slice(7))\n }\n}\n\n// ── Framework adapters ──────────────────────────────────────────────────────\n\n// Express-style middleware. Adds `req.user` on success.\nexport function expressMiddleware(verifier: TillAuthVerifier, opts: { onError?: (err: TillAuthVerifyError) => unknown } = {}) {\n return async function (req: ExpressLikeReq, res: ExpressLikeRes, next: () => void) {\n try {\n const h = req.headers?.authorization\n const claims = await verifier.verifyHeader(Array.isArray(h) ? h[0] : h)\n ;(req as ExpressLikeReq & { user: AuthClaims }).user = claims\n next()\n } catch (e) {\n const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError('Auth failed', 'invalid_token')\n if (opts.onError) {\n const out = opts.onError(err)\n if (out !== undefined) {\n res.status(401).json(out as Record<string, unknown>)\n return\n }\n }\n res.status(401).json({ error: err.message, code: err.code })\n }\n }\n}\n\ninterface ExpressLikeReq {\n headers?: { authorization?: string | string[] }\n}\ninterface ExpressLikeRes {\n status: (n: number) => { json: (b: Record<string, unknown>) => void }\n}\n\n// Fastify plugin shape — not bound to Fastify's types to avoid a peer dep.\nexport function fastifyHook(verifier: TillAuthVerifier) {\n return async function (\n req: { headers: Record<string, string | string[] | undefined>; user?: AuthClaims },\n reply: { code: (n: number) => { send: (b: unknown) => void } },\n ) {\n try {\n const h = req.headers['authorization']\n const auth = Array.isArray(h) ? h[0] : h\n const claims = await verifier.verifyHeader(auth)\n req.user = claims\n } catch (e) {\n const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError('Auth failed', 'invalid_token')\n reply.code(401).send({ error: err.message, code: err.code })\n }\n }\n}\n\n// Convenience entrypoint for users who want a one-call setup.\nexport function createVerifier(opts: VerifyOptions): TillAuthVerifier {\n return new TillAuthVerifier(opts)\n}\n\nexport { createFetchHandler, expressCookieProxy } from './cookie-proxy.js'\nexport type { CookieProxyOptions } from './cookie-proxy.js'\n"]}
@@ -0,0 +1,115 @@
1
+ import { JWK } from 'jose';
2
+
3
+ interface CookieProxyOptions {
4
+ /** TillAuth public app id (`tau_…`). */
5
+ appId: string;
6
+ /** Override the TillAuth API base. */
7
+ apiBase?: string;
8
+ /** Cookie name for the access token. Default `tau_at`. */
9
+ accessCookie?: string;
10
+ /** Cookie name for the refresh token. Default `tau_rt`. */
11
+ refreshCookie?: string;
12
+ /** Cookie path. Default '/'. */
13
+ cookiePath?: string;
14
+ /** Cookie domain (e.g. `.example.com` to share across subdomains). */
15
+ cookieDomain?: string;
16
+ /** Secure flag. Defaults to true in production, false otherwise. */
17
+ secure?: boolean;
18
+ }
19
+ declare function createFetchHandler(opts: CookieProxyOptions): (req: Request, ctx?: {
20
+ params?: {
21
+ path?: string | string[];
22
+ };
23
+ }) => Promise<Response>;
24
+ interface ExpReq {
25
+ method: string;
26
+ url?: string;
27
+ originalUrl?: string;
28
+ path?: string;
29
+ body?: unknown;
30
+ headers: Record<string, string | string[] | undefined>;
31
+ }
32
+ interface ExpRes {
33
+ status(n: number): ExpRes;
34
+ setHeader(name: string, value: string | string[]): void;
35
+ json(body: unknown): void;
36
+ }
37
+ declare function expressCookieProxy(opts: CookieProxyOptions): (req: ExpReq, res: ExpRes) => Promise<void>;
38
+
39
+ interface VerifyOptions {
40
+ /** TillAuth public app id (`tau_…`). Used to enforce app scoping. */
41
+ appId: string;
42
+ /** TillAuth API base. Defaults to https://auth.tilldev.dev */
43
+ apiBase?: string;
44
+ /**
45
+ * Inline JWKS as a JWK array (the same `publicJwk` entries you'd find in
46
+ * the TILLAUTH_JWT_KEYS env). Use this in environments where you want
47
+ * fully air-gapped verification.
48
+ */
49
+ publicJwks?: JWK[];
50
+ /** Require email_verified=true. Defaults to false. */
51
+ requireVerifiedEmail?: boolean;
52
+ /** Require MFA was satisfied this session. Defaults to false. */
53
+ requireMfa?: boolean;
54
+ }
55
+ interface AuthClaims {
56
+ /** User id */
57
+ sub: string;
58
+ /** App id the token was issued for */
59
+ app: string;
60
+ /** Lowercased email */
61
+ email: string;
62
+ /** Whether MFA was satisfied this session */
63
+ mfa: boolean;
64
+ /**
65
+ * Whether the account's email was verified at issue time. Optional: tokens
66
+ * minted before this claim existed omit it. When `requireVerifiedEmail` is
67
+ * set, an absent claim is treated as unverified (fail-closed on the check).
68
+ */
69
+ email_verified?: boolean;
70
+ /** Issued-at (seconds) */
71
+ iat: number;
72
+ /** Expires-at (seconds) */
73
+ exp: number;
74
+ }
75
+ declare class TillAuthVerifyError extends Error {
76
+ code: 'no_token' | 'invalid_token' | 'wrong_app' | 'mfa_required' | 'email_not_verified';
77
+ constructor(message: string, code: TillAuthVerifyError['code']);
78
+ }
79
+ declare class TillAuthVerifier {
80
+ private readonly opts;
81
+ private readonly remote;
82
+ private readonly inlineKeys;
83
+ constructor(opts: VerifyOptions);
84
+ verify(token: string): Promise<AuthClaims>;
85
+ private applyClaimsChecks;
86
+ /**
87
+ * Pull a Bearer token out of an Authorization header and verify. Returns
88
+ * the claims or throws TillAuthVerifyError.
89
+ */
90
+ verifyHeader(authHeader: string | undefined | null): Promise<AuthClaims>;
91
+ }
92
+ declare function expressMiddleware(verifier: TillAuthVerifier, opts?: {
93
+ onError?: (err: TillAuthVerifyError) => unknown;
94
+ }): (req: ExpressLikeReq, res: ExpressLikeRes, next: () => void) => Promise<void>;
95
+ interface ExpressLikeReq {
96
+ headers?: {
97
+ authorization?: string | string[];
98
+ };
99
+ }
100
+ interface ExpressLikeRes {
101
+ status: (n: number) => {
102
+ json: (b: Record<string, unknown>) => void;
103
+ };
104
+ }
105
+ declare function fastifyHook(verifier: TillAuthVerifier): (req: {
106
+ headers: Record<string, string | string[] | undefined>;
107
+ user?: AuthClaims;
108
+ }, reply: {
109
+ code: (n: number) => {
110
+ send: (b: unknown) => void;
111
+ };
112
+ }) => Promise<void>;
113
+ declare function createVerifier(opts: VerifyOptions): TillAuthVerifier;
114
+
115
+ export { type AuthClaims, type CookieProxyOptions, TillAuthVerifier, TillAuthVerifyError, type VerifyOptions, createFetchHandler, createVerifier, expressCookieProxy, expressMiddleware, fastifyHook };
@@ -0,0 +1,115 @@
1
+ import { JWK } from 'jose';
2
+
3
+ interface CookieProxyOptions {
4
+ /** TillAuth public app id (`tau_…`). */
5
+ appId: string;
6
+ /** Override the TillAuth API base. */
7
+ apiBase?: string;
8
+ /** Cookie name for the access token. Default `tau_at`. */
9
+ accessCookie?: string;
10
+ /** Cookie name for the refresh token. Default `tau_rt`. */
11
+ refreshCookie?: string;
12
+ /** Cookie path. Default '/'. */
13
+ cookiePath?: string;
14
+ /** Cookie domain (e.g. `.example.com` to share across subdomains). */
15
+ cookieDomain?: string;
16
+ /** Secure flag. Defaults to true in production, false otherwise. */
17
+ secure?: boolean;
18
+ }
19
+ declare function createFetchHandler(opts: CookieProxyOptions): (req: Request, ctx?: {
20
+ params?: {
21
+ path?: string | string[];
22
+ };
23
+ }) => Promise<Response>;
24
+ interface ExpReq {
25
+ method: string;
26
+ url?: string;
27
+ originalUrl?: string;
28
+ path?: string;
29
+ body?: unknown;
30
+ headers: Record<string, string | string[] | undefined>;
31
+ }
32
+ interface ExpRes {
33
+ status(n: number): ExpRes;
34
+ setHeader(name: string, value: string | string[]): void;
35
+ json(body: unknown): void;
36
+ }
37
+ declare function expressCookieProxy(opts: CookieProxyOptions): (req: ExpReq, res: ExpRes) => Promise<void>;
38
+
39
+ interface VerifyOptions {
40
+ /** TillAuth public app id (`tau_…`). Used to enforce app scoping. */
41
+ appId: string;
42
+ /** TillAuth API base. Defaults to https://auth.tilldev.dev */
43
+ apiBase?: string;
44
+ /**
45
+ * Inline JWKS as a JWK array (the same `publicJwk` entries you'd find in
46
+ * the TILLAUTH_JWT_KEYS env). Use this in environments where you want
47
+ * fully air-gapped verification.
48
+ */
49
+ publicJwks?: JWK[];
50
+ /** Require email_verified=true. Defaults to false. */
51
+ requireVerifiedEmail?: boolean;
52
+ /** Require MFA was satisfied this session. Defaults to false. */
53
+ requireMfa?: boolean;
54
+ }
55
+ interface AuthClaims {
56
+ /** User id */
57
+ sub: string;
58
+ /** App id the token was issued for */
59
+ app: string;
60
+ /** Lowercased email */
61
+ email: string;
62
+ /** Whether MFA was satisfied this session */
63
+ mfa: boolean;
64
+ /**
65
+ * Whether the account's email was verified at issue time. Optional: tokens
66
+ * minted before this claim existed omit it. When `requireVerifiedEmail` is
67
+ * set, an absent claim is treated as unverified (fail-closed on the check).
68
+ */
69
+ email_verified?: boolean;
70
+ /** Issued-at (seconds) */
71
+ iat: number;
72
+ /** Expires-at (seconds) */
73
+ exp: number;
74
+ }
75
+ declare class TillAuthVerifyError extends Error {
76
+ code: 'no_token' | 'invalid_token' | 'wrong_app' | 'mfa_required' | 'email_not_verified';
77
+ constructor(message: string, code: TillAuthVerifyError['code']);
78
+ }
79
+ declare class TillAuthVerifier {
80
+ private readonly opts;
81
+ private readonly remote;
82
+ private readonly inlineKeys;
83
+ constructor(opts: VerifyOptions);
84
+ verify(token: string): Promise<AuthClaims>;
85
+ private applyClaimsChecks;
86
+ /**
87
+ * Pull a Bearer token out of an Authorization header and verify. Returns
88
+ * the claims or throws TillAuthVerifyError.
89
+ */
90
+ verifyHeader(authHeader: string | undefined | null): Promise<AuthClaims>;
91
+ }
92
+ declare function expressMiddleware(verifier: TillAuthVerifier, opts?: {
93
+ onError?: (err: TillAuthVerifyError) => unknown;
94
+ }): (req: ExpressLikeReq, res: ExpressLikeRes, next: () => void) => Promise<void>;
95
+ interface ExpressLikeReq {
96
+ headers?: {
97
+ authorization?: string | string[];
98
+ };
99
+ }
100
+ interface ExpressLikeRes {
101
+ status: (n: number) => {
102
+ json: (b: Record<string, unknown>) => void;
103
+ };
104
+ }
105
+ declare function fastifyHook(verifier: TillAuthVerifier): (req: {
106
+ headers: Record<string, string | string[] | undefined>;
107
+ user?: AuthClaims;
108
+ }, reply: {
109
+ code: (n: number) => {
110
+ send: (b: unknown) => void;
111
+ };
112
+ }) => Promise<void>;
113
+ declare function createVerifier(opts: VerifyOptions): TillAuthVerifier;
114
+
115
+ export { type AuthClaims, type CookieProxyOptions, TillAuthVerifier, TillAuthVerifyError, type VerifyOptions, createFetchHandler, createVerifier, expressCookieProxy, expressMiddleware, fastifyHook };
package/dist/index.js ADDED
@@ -0,0 +1,261 @@
1
+ import { importJWK, createRemoteJWKSet, jwtVerify } from 'jose';
2
+
3
+ // src/index.ts
4
+
5
+ // src/cookie-proxy.ts
6
+ var DEFAULT_API = "https://auth.tilldev.dev";
7
+ function resolve(opts) {
8
+ return {
9
+ appId: opts.appId,
10
+ apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\/$/, ""),
11
+ accessCookie: opts.accessCookie ?? "tau_at",
12
+ refreshCookie: opts.refreshCookie ?? "tau_rt",
13
+ cookiePath: opts.cookiePath ?? "/",
14
+ cookieDomain: opts.cookieDomain ?? "",
15
+ secure: opts.secure ?? process.env.NODE_ENV === "production"
16
+ };
17
+ }
18
+ function makeCookie(name, value, o, opts = {}) {
19
+ const parts = [`${name}=${opts.clear ? "" : value}`];
20
+ parts.push("HttpOnly");
21
+ if (o.secure) parts.push("Secure");
22
+ parts.push("SameSite=Lax");
23
+ parts.push(`Path=${o.cookiePath}`);
24
+ if (o.cookieDomain) parts.push(`Domain=${o.cookieDomain}`);
25
+ if (opts.clear) parts.push("Max-Age=0");
26
+ else if (opts.maxAge !== void 0) parts.push(`Max-Age=${opts.maxAge}`);
27
+ return parts.join("; ");
28
+ }
29
+ async function handleProxy(req, raw) {
30
+ const opts = resolve(raw);
31
+ const path = req.pathname.replace(/^\/+/, "");
32
+ const url = `${opts.apiBase}/v1/${path}`;
33
+ const headers = {
34
+ "Content-Type": "application/json",
35
+ "X-TillAuth-App": opts.appId,
36
+ "User-Agent": "tilldev-auth-node/cookie-proxy"
37
+ };
38
+ let body = req.body;
39
+ if (path === "me" && req.cookies[opts.accessCookie]) {
40
+ headers.Authorization = `Bearer ${req.cookies[opts.accessCookie]}`;
41
+ }
42
+ if (path === "refresh") {
43
+ const rt = req.cookies[opts.refreshCookie];
44
+ if (!rt) {
45
+ return {
46
+ status: 401,
47
+ body: JSON.stringify({ error: "no refresh cookie" }),
48
+ setCookies: [],
49
+ headers: { "Content-Type": "application/json" }
50
+ };
51
+ }
52
+ body = JSON.stringify({ refresh_token: rt });
53
+ }
54
+ if (path === "signout") {
55
+ const rt = req.cookies[opts.refreshCookie];
56
+ body = JSON.stringify({ refresh_token: rt ?? "" });
57
+ }
58
+ const upstream = await fetch(url, { method: req.method, headers, body });
59
+ const text = await upstream.text();
60
+ let json = {};
61
+ try {
62
+ json = JSON.parse(text);
63
+ } catch {
64
+ json = {};
65
+ }
66
+ const setCookies = [];
67
+ const out = { ...json };
68
+ if (typeof json.access_token === "string") {
69
+ setCookies.push(makeCookie(opts.accessCookie, json.access_token, opts, { maxAge: 60 * 10 }));
70
+ delete out.access_token;
71
+ }
72
+ if (typeof json.refresh_token === "string") {
73
+ setCookies.push(makeCookie(opts.refreshCookie, json.refresh_token, opts, { maxAge: 60 * 60 * 24 * 30 }));
74
+ delete out.refresh_token;
75
+ delete out.refresh_expires_at;
76
+ }
77
+ if (path === "signout") {
78
+ setCookies.push(makeCookie(opts.accessCookie, "", opts, { clear: true }));
79
+ setCookies.push(makeCookie(opts.refreshCookie, "", opts, { clear: true }));
80
+ }
81
+ return {
82
+ status: upstream.status,
83
+ body: JSON.stringify(out),
84
+ setCookies,
85
+ headers: { "Content-Type": "application/json" }
86
+ };
87
+ }
88
+ function createFetchHandler(opts) {
89
+ return async function handler(req, ctx = {}) {
90
+ const url = new URL(req.url);
91
+ let pathname;
92
+ if (ctx.params?.path) {
93
+ pathname = Array.isArray(ctx.params.path) ? `/${ctx.params.path.join("/")}` : `/${ctx.params.path}`;
94
+ } else {
95
+ pathname = url.pathname.replace(/^\/api\/auth/, "");
96
+ }
97
+ const cookies = parseCookieHeader(req.headers.get("cookie"));
98
+ const body = req.method === "POST" ? await req.text() : "{}";
99
+ const out = await handleProxy({ method: req.method, pathname, body, cookies }, opts);
100
+ const headers = new Headers(out.headers);
101
+ for (const c of out.setCookies) headers.append("Set-Cookie", c);
102
+ return new Response(out.body, { status: out.status, headers });
103
+ };
104
+ }
105
+ function expressCookieProxy(opts) {
106
+ return async function(req, res) {
107
+ const path = req.path ?? (req.originalUrl ?? req.url ?? "/").replace(/^\/api\/auth/, "").split("?")[0] ?? "/";
108
+ const cookieHeader = typeof req.headers.cookie === "string" ? req.headers.cookie : Array.isArray(req.headers.cookie) ? req.headers.cookie[0] : "";
109
+ const body = typeof req.body === "string" ? req.body : req.body ? JSON.stringify(req.body) : "{}";
110
+ const out = await handleProxy(
111
+ {
112
+ method: req.method,
113
+ pathname: path,
114
+ body,
115
+ cookies: parseCookieHeader(cookieHeader ?? null)
116
+ },
117
+ opts
118
+ );
119
+ res.status(out.status);
120
+ if (out.setCookies.length > 0) res.setHeader("Set-Cookie", out.setCookies);
121
+ for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v);
122
+ res.json(JSON.parse(out.body));
123
+ };
124
+ }
125
+ function parseCookieHeader(header) {
126
+ const out = {};
127
+ if (!header) return out;
128
+ for (const part of header.split(";")) {
129
+ const [k, ...rest] = part.trim().split("=");
130
+ if (!k) continue;
131
+ out[k] = decodeURIComponent(rest.join("="));
132
+ }
133
+ return out;
134
+ }
135
+
136
+ // src/index.ts
137
+ var DEFAULT_API2 = "https://auth.tilldev.dev";
138
+ var ISSUER = "tillauth";
139
+ var TillAuthVerifyError = class extends Error {
140
+ constructor(message, code) {
141
+ super(message);
142
+ this.name = "TillAuthVerifyError";
143
+ this.code = code;
144
+ }
145
+ };
146
+ var TillAuthVerifier = class {
147
+ constructor(opts) {
148
+ if (!opts.appId) throw new Error("TillAuthVerifier: appId is required");
149
+ this.opts = {
150
+ appId: opts.appId,
151
+ apiBase: (opts.apiBase ?? DEFAULT_API2).replace(/\/$/, ""),
152
+ requireVerifiedEmail: opts.requireVerifiedEmail ?? false,
153
+ requireMfa: opts.requireMfa ?? false
154
+ };
155
+ if (opts.publicJwks && opts.publicJwks.length > 0) {
156
+ this.remote = null;
157
+ this.inlineKeys = Promise.all(
158
+ opts.publicJwks.map(async (k) => ({ kid: k.kid, key: await importJWK(k, "EdDSA") }))
159
+ );
160
+ } else {
161
+ this.remote = createRemoteJWKSet(new URL(`${this.opts.apiBase}/.well-known/jwks.json`));
162
+ this.inlineKeys = null;
163
+ }
164
+ }
165
+ async verify(token) {
166
+ if (!token) throw new TillAuthVerifyError("No token", "no_token");
167
+ let claims;
168
+ try {
169
+ if (this.inlineKeys) {
170
+ const keys = await this.inlineKeys;
171
+ let lastErr;
172
+ for (const k of keys) {
173
+ try {
174
+ const { payload: payload2 } = await jwtVerify(token, k.key, {
175
+ algorithms: ["EdDSA"],
176
+ issuer: ISSUER
177
+ });
178
+ claims = payload2;
179
+ return this.applyClaimsChecks(claims);
180
+ } catch (e) {
181
+ lastErr = e;
182
+ }
183
+ }
184
+ throw lastErr ?? new Error("No key matched");
185
+ }
186
+ const { payload } = await jwtVerify(token, this.remote, {
187
+ algorithms: ["EdDSA"],
188
+ issuer: ISSUER
189
+ });
190
+ claims = payload;
191
+ } catch (e) {
192
+ throw new TillAuthVerifyError(
193
+ e instanceof Error ? e.message : "Invalid token",
194
+ "invalid_token"
195
+ );
196
+ }
197
+ return this.applyClaimsChecks(claims);
198
+ }
199
+ applyClaimsChecks(claims) {
200
+ if (claims.app !== this.opts.appId) {
201
+ throw new TillAuthVerifyError(`Token issued for different app`, "wrong_app");
202
+ }
203
+ if (this.opts.requireMfa && !claims.mfa) {
204
+ throw new TillAuthVerifyError("MFA required", "mfa_required");
205
+ }
206
+ if (this.opts.requireVerifiedEmail && claims.email_verified !== true) {
207
+ throw new TillAuthVerifyError("Email not verified", "email_not_verified");
208
+ }
209
+ return claims;
210
+ }
211
+ /**
212
+ * Pull a Bearer token out of an Authorization header and verify. Returns
213
+ * the claims or throws TillAuthVerifyError.
214
+ */
215
+ async verifyHeader(authHeader) {
216
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
217
+ throw new TillAuthVerifyError("Missing Bearer token", "no_token");
218
+ }
219
+ return this.verify(authHeader.slice(7));
220
+ }
221
+ };
222
+ function expressMiddleware(verifier, opts = {}) {
223
+ return async function(req, res, next) {
224
+ try {
225
+ const h = req.headers?.authorization;
226
+ const claims = await verifier.verifyHeader(Array.isArray(h) ? h[0] : h);
227
+ req.user = claims;
228
+ next();
229
+ } catch (e) {
230
+ const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError("Auth failed", "invalid_token");
231
+ if (opts.onError) {
232
+ const out = opts.onError(err);
233
+ if (out !== void 0) {
234
+ res.status(401).json(out);
235
+ return;
236
+ }
237
+ }
238
+ res.status(401).json({ error: err.message, code: err.code });
239
+ }
240
+ };
241
+ }
242
+ function fastifyHook(verifier) {
243
+ return async function(req, reply) {
244
+ try {
245
+ const h = req.headers["authorization"];
246
+ const auth = Array.isArray(h) ? h[0] : h;
247
+ const claims = await verifier.verifyHeader(auth);
248
+ req.user = claims;
249
+ } catch (e) {
250
+ const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError("Auth failed", "invalid_token");
251
+ reply.code(401).send({ error: err.message, code: err.code });
252
+ }
253
+ };
254
+ }
255
+ function createVerifier(opts) {
256
+ return new TillAuthVerifier(opts);
257
+ }
258
+
259
+ export { TillAuthVerifier, TillAuthVerifyError, createFetchHandler, createVerifier, expressCookieProxy, expressMiddleware, fastifyHook };
260
+ //# sourceMappingURL=index.js.map
261
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cook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,EAAA,OAAO,IAAI,iBAAiB,IAAI,CAAA;AAClC","file":"index.js","sourcesContent":["// Cookie-mode proxy for TillAuth.\n//\n// Mount this on the customer's backend (typically at /api/auth/*). It\n// forwards JSON bodies to TillAuth's /v1/* endpoints, then translates\n// access_token + refresh_token in the response into HttpOnly cookies on\n// the customer's domain. The browser's localStorage never sees the\n// tokens — XSS can't exfiltrate them.\n//\n// Two adapters: a generic web-fetch handler (Cloudflare Workers, Next.js\n// Route Handlers, Bun, Deno) and an Express middleware. Pick one.\n\nconst DEFAULT_API = 'https://auth.tilldev.dev'\n\nexport interface CookieProxyOptions {\n /** TillAuth public app id (`tau_…`). */\n appId: string\n /** Override the TillAuth API base. */\n apiBase?: string\n /** Cookie name for the access token. Default `tau_at`. */\n accessCookie?: string\n /** Cookie name for the refresh token. Default `tau_rt`. */\n refreshCookie?: string\n /** Cookie path. Default '/'. */\n cookiePath?: string\n /** Cookie domain (e.g. `.example.com` to share across subdomains). */\n cookieDomain?: string\n /** Secure flag. Defaults to true in production, false otherwise. */\n secure?: boolean\n}\n\ninterface NormalizedRequest {\n method: string\n pathname: string // path relative to the mount point (`/signin`, `/refresh`)\n body: string\n cookies: Record<string, string>\n}\ninterface NormalizedResponse {\n status: number\n body: string\n setCookies: string[]\n headers: Record<string, string>\n}\n\ninterface AuthBody {\n access_token?: string\n refresh_token?: string\n refresh_expires_at?: string\n [key: string]: unknown\n}\n\nfunction resolve(opts: CookieProxyOptions): Required<CookieProxyOptions> {\n return {\n appId: opts.appId,\n apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\\/$/, ''),\n accessCookie: opts.accessCookie ?? 'tau_at',\n refreshCookie: opts.refreshCookie ?? 'tau_rt',\n cookiePath: opts.cookiePath ?? '/',\n cookieDomain: opts.cookieDomain ?? '',\n secure: opts.secure ?? process.env.NODE_ENV === 'production',\n }\n}\n\nfunction makeCookie(\n name: string,\n value: string,\n o: Required<CookieProxyOptions>,\n opts: { maxAge?: number; clear?: boolean } = {},\n): string {\n const parts = [`${name}=${opts.clear ? '' : value}`]\n parts.push('HttpOnly')\n if (o.secure) parts.push('Secure')\n parts.push('SameSite=Lax')\n parts.push(`Path=${o.cookiePath}`)\n if (o.cookieDomain) parts.push(`Domain=${o.cookieDomain}`)\n if (opts.clear) parts.push('Max-Age=0')\n else if (opts.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`)\n return parts.join('; ')\n}\n\nasync function handleProxy(req: NormalizedRequest, raw: CookieProxyOptions): Promise<NormalizedResponse> {\n const opts = resolve(raw)\n const path = req.pathname.replace(/^\\/+/, '')\n\n // Map proxy paths → TillAuth paths.\n const url = `${opts.apiBase}/v1/${path}`\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'X-TillAuth-App': opts.appId,\n 'User-Agent': 'tilldev-auth-node/cookie-proxy',\n }\n\n // /me, /refresh, /signout need to carry tokens from cookies, not the body.\n let body = req.body\n if (path === 'me' && req.cookies[opts.accessCookie]) {\n headers.Authorization = `Bearer ${req.cookies[opts.accessCookie]}`\n }\n if (path === 'refresh') {\n const rt = req.cookies[opts.refreshCookie]\n if (!rt) {\n return {\n status: 401,\n body: JSON.stringify({ error: 'no refresh cookie' }),\n setCookies: [],\n headers: { 'Content-Type': 'application/json' },\n }\n }\n body = JSON.stringify({ refresh_token: rt })\n }\n if (path === 'signout') {\n const rt = req.cookies[opts.refreshCookie]\n body = JSON.stringify({ refresh_token: rt ?? '' })\n }\n\n const upstream = await fetch(url, { method: req.method, headers, body })\n const text = await upstream.text()\n let json: AuthBody = {}\n try {\n json = JSON.parse(text) as AuthBody\n } catch {\n json = {}\n }\n\n const setCookies: string[] = []\n // Always strip token fields before returning to the SPA.\n const out = { ...json }\n\n if (typeof json.access_token === 'string') {\n setCookies.push(makeCookie(opts.accessCookie, json.access_token, opts, { maxAge: 60 * 10 }))\n delete out.access_token\n }\n if (typeof json.refresh_token === 'string') {\n // 30d in line with the Fastify REFRESH_TTL_MS.\n setCookies.push(makeCookie(opts.refreshCookie, json.refresh_token, opts, { maxAge: 60 * 60 * 24 * 30 }))\n delete out.refresh_token\n delete out.refresh_expires_at\n }\n if (path === 'signout') {\n setCookies.push(makeCookie(opts.accessCookie, '', opts, { clear: true }))\n setCookies.push(makeCookie(opts.refreshCookie, '', opts, { clear: true }))\n }\n\n return {\n status: upstream.status,\n body: JSON.stringify(out),\n setCookies,\n headers: { 'Content-Type': 'application/json' },\n }\n}\n\n// ── Adapter 1: web-fetch (Next.js Route Handlers, Workers, Bun, Deno) ───────\n\nexport function createFetchHandler(opts: CookieProxyOptions) {\n return async function handler(req: Request, ctx: { params?: { path?: string | string[] } } = {}): Promise<Response> {\n const url = new URL(req.url)\n // Derive the proxy-relative path. Prefer ctx.params.path (Next.js catch-all);\n // fall back to the part of the URL after the mount point heuristic.\n let pathname: string\n if (ctx.params?.path) {\n pathname = Array.isArray(ctx.params.path) ? `/${ctx.params.path.join('/')}` : `/${ctx.params.path}`\n } else {\n pathname = url.pathname.replace(/^\\/api\\/auth/, '')\n }\n const cookies = parseCookieHeader(req.headers.get('cookie'))\n const body = req.method === 'POST' ? await req.text() : '{}'\n const out = await handleProxy({ method: req.method, pathname, body, cookies }, opts)\n const headers = new Headers(out.headers)\n for (const c of out.setCookies) headers.append('Set-Cookie', c)\n return new Response(out.body, { status: out.status, headers })\n }\n}\n\n// ── Adapter 2: Express ──────────────────────────────────────────────────────\n\ninterface ExpReq {\n method: string\n url?: string\n originalUrl?: string\n path?: string\n body?: unknown\n headers: Record<string, string | string[] | undefined>\n}\ninterface ExpRes {\n status(n: number): ExpRes\n setHeader(name: string, value: string | string[]): void\n json(body: unknown): void\n}\n\nexport function expressCookieProxy(opts: CookieProxyOptions) {\n return async function (req: ExpReq, res: ExpRes): Promise<void> {\n const path =\n req.path ?? (req.originalUrl ?? req.url ?? '/').replace(/^\\/api\\/auth/, '').split('?')[0] ?? '/'\n const cookieHeader =\n typeof req.headers.cookie === 'string' ? req.headers.cookie : Array.isArray(req.headers.cookie) ? req.headers.cookie[0] : ''\n const body =\n typeof req.body === 'string' ? req.body : req.body ? JSON.stringify(req.body) : '{}'\n const out = await handleProxy(\n {\n method: req.method,\n pathname: path,\n body,\n cookies: parseCookieHeader(cookieHeader ?? null),\n },\n opts,\n )\n res.status(out.status)\n if (out.setCookies.length > 0) res.setHeader('Set-Cookie', out.setCookies)\n for (const [k, v] of Object.entries(out.headers)) res.setHeader(k, v)\n res.json(JSON.parse(out.body))\n }\n}\n\nfunction parseCookieHeader(header: string | null): Record<string, string> {\n const out: Record<string, string> = {}\n if (!header) return out\n for (const part of header.split(';')) {\n const [k, ...rest] = part.trim().split('=')\n if (!k) continue\n out[k] = decodeURIComponent(rest.join('='))\n }\n return out\n}\n","import { jwtVerify, createRemoteJWKSet, importJWK, type JWK } from 'jose'\n\n// Server-side TillAuth verification.\n//\n// You configure once with the issuer + JWKS endpoint (or inline public keys),\n// then call `verify(token)` or use the framework-specific middleware.\n//\n// Verification is offline against the cached JWKS — no round-trip to TillAuth\n// on the hot path.\n\nconst DEFAULT_API = 'https://auth.tilldev.dev'\nconst ISSUER = 'tillauth'\n\nexport interface VerifyOptions {\n /** TillAuth public app id (`tau_…`). Used to enforce app scoping. */\n appId: string\n /** TillAuth API base. Defaults to https://auth.tilldev.dev */\n apiBase?: string\n /**\n * Inline JWKS as a JWK array (the same `publicJwk` entries you'd find in\n * the TILLAUTH_JWT_KEYS env). Use this in environments where you want\n * fully air-gapped verification.\n */\n publicJwks?: JWK[]\n /** Require email_verified=true. Defaults to false. */\n requireVerifiedEmail?: boolean\n /** Require MFA was satisfied this session. Defaults to false. */\n requireMfa?: boolean\n}\n\nexport interface AuthClaims {\n /** User id */\n sub: string\n /** App id the token was issued for */\n app: string\n /** Lowercased email */\n email: string\n /** Whether MFA was satisfied this session */\n mfa: boolean\n /**\n * Whether the account's email was verified at issue time. Optional: tokens\n * minted before this claim existed omit it. When `requireVerifiedEmail` is\n * set, an absent claim is treated as unverified (fail-closed on the check).\n */\n email_verified?: boolean\n /** Issued-at (seconds) */\n iat: number\n /** Expires-at (seconds) */\n exp: number\n}\n\nexport class TillAuthVerifyError extends Error {\n code: 'no_token' | 'invalid_token' | 'wrong_app' | 'mfa_required' | 'email_not_verified'\n constructor(message: string, code: TillAuthVerifyError['code']) {\n super(message)\n this.name = 'TillAuthVerifyError'\n this.code = code\n }\n}\n\nexport class TillAuthVerifier {\n private readonly opts: Required<Pick<VerifyOptions, 'appId' | 'apiBase' | 'requireVerifiedEmail' | 'requireMfa'>>\n private readonly remote: ReturnType<typeof createRemoteJWKSet> | null\n private readonly inlineKeys: Promise<Array<{ kid?: string; key: Awaited<ReturnType<typeof importJWK>> }>> | null\n\n constructor(opts: VerifyOptions) {\n if (!opts.appId) throw new Error('TillAuthVerifier: appId is required')\n this.opts = {\n appId: opts.appId,\n apiBase: (opts.apiBase ?? DEFAULT_API).replace(/\\/$/, ''),\n requireVerifiedEmail: opts.requireVerifiedEmail ?? false,\n requireMfa: opts.requireMfa ?? false,\n }\n if (opts.publicJwks && opts.publicJwks.length > 0) {\n this.remote = null\n this.inlineKeys = Promise.all(\n opts.publicJwks.map(async (k) => ({ kid: k.kid, key: await importJWK(k, 'EdDSA') })),\n )\n } else {\n this.remote = createRemoteJWKSet(new URL(`${this.opts.apiBase}/.well-known/jwks.json`))\n this.inlineKeys = null\n }\n }\n\n async verify(token: string): Promise<AuthClaims> {\n if (!token) throw new TillAuthVerifyError('No token', 'no_token')\n\n let claims: AuthClaims\n try {\n if (this.inlineKeys) {\n const keys = await this.inlineKeys\n let lastErr: unknown\n for (const k of keys) {\n try {\n const { payload } = await jwtVerify(token, k.key, {\n algorithms: ['EdDSA'],\n issuer: ISSUER,\n })\n claims = payload as unknown as AuthClaims\n return this.applyClaimsChecks(claims)\n } catch (e) {\n lastErr = e\n }\n }\n throw lastErr ?? new Error('No key matched')\n }\n const { payload } = await jwtVerify(token, this.remote!, {\n algorithms: ['EdDSA'],\n issuer: ISSUER,\n })\n claims = payload as unknown as AuthClaims\n } catch (e) {\n throw new TillAuthVerifyError(\n e instanceof Error ? e.message : 'Invalid token',\n 'invalid_token',\n )\n }\n return this.applyClaimsChecks(claims)\n }\n\n private applyClaimsChecks(claims: AuthClaims): AuthClaims {\n if (claims.app !== this.opts.appId) {\n throw new TillAuthVerifyError(`Token issued for different app`, 'wrong_app')\n }\n if (this.opts.requireMfa && !claims.mfa) {\n throw new TillAuthVerifyError('MFA required', 'mfa_required')\n }\n // Absent claim (older tokens) is treated as unverified only when the check\n // is enabled — so requireVerifiedEmail fails closed rather than silently\n // passing when the issuer predates the claim.\n if (this.opts.requireVerifiedEmail && claims.email_verified !== true) {\n throw new TillAuthVerifyError('Email not verified', 'email_not_verified')\n }\n return claims\n }\n\n /**\n * Pull a Bearer token out of an Authorization header and verify. Returns\n * the claims or throws TillAuthVerifyError.\n */\n async verifyHeader(authHeader: string | undefined | null): Promise<AuthClaims> {\n if (!authHeader || !authHeader.startsWith('Bearer ')) {\n throw new TillAuthVerifyError('Missing Bearer token', 'no_token')\n }\n return this.verify(authHeader.slice(7))\n }\n}\n\n// ── Framework adapters ──────────────────────────────────────────────────────\n\n// Express-style middleware. Adds `req.user` on success.\nexport function expressMiddleware(verifier: TillAuthVerifier, opts: { onError?: (err: TillAuthVerifyError) => unknown } = {}) {\n return async function (req: ExpressLikeReq, res: ExpressLikeRes, next: () => void) {\n try {\n const h = req.headers?.authorization\n const claims = await verifier.verifyHeader(Array.isArray(h) ? h[0] : h)\n ;(req as ExpressLikeReq & { user: AuthClaims }).user = claims\n next()\n } catch (e) {\n const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError('Auth failed', 'invalid_token')\n if (opts.onError) {\n const out = opts.onError(err)\n if (out !== undefined) {\n res.status(401).json(out as Record<string, unknown>)\n return\n }\n }\n res.status(401).json({ error: err.message, code: err.code })\n }\n }\n}\n\ninterface ExpressLikeReq {\n headers?: { authorization?: string | string[] }\n}\ninterface ExpressLikeRes {\n status: (n: number) => { json: (b: Record<string, unknown>) => void }\n}\n\n// Fastify plugin shape — not bound to Fastify's types to avoid a peer dep.\nexport function fastifyHook(verifier: TillAuthVerifier) {\n return async function (\n req: { headers: Record<string, string | string[] | undefined>; user?: AuthClaims },\n reply: { code: (n: number) => { send: (b: unknown) => void } },\n ) {\n try {\n const h = req.headers['authorization']\n const auth = Array.isArray(h) ? h[0] : h\n const claims = await verifier.verifyHeader(auth)\n req.user = claims\n } catch (e) {\n const err = e instanceof TillAuthVerifyError ? e : new TillAuthVerifyError('Auth failed', 'invalid_token')\n reply.code(401).send({ error: err.message, code: err.code })\n }\n }\n}\n\n// Convenience entrypoint for users who want a one-call setup.\nexport function createVerifier(opts: VerifyOptions): TillAuthVerifier {\n return new TillAuthVerifier(opts)\n}\n\nexport { createFetchHandler, expressCookieProxy } from './cookie-proxy.js'\nexport type { CookieProxyOptions } from './cookie-proxy.js'\n"]}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@tillstack/auth-node",
3
+ "version": "0.1.0",
4
+ "description": "Node SDK for TillAuth — JWT verification + middleware",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": {
14
+ "types": "./dist/index.d.mts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "sideEffects": false,
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "dependencies": {
29
+ "jose": "^5.9.6"
30
+ },
31
+ "devDependencies": {
32
+ "tsup": "^8.3.5",
33
+ "typescript": "^5.7.3"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/tillafrica/tilldev.git",
38
+ "directory": "packages/sdk-auth-node"
39
+ },
40
+ "homepage": "https://tilldev.dev",
41
+ "bugs": {
42
+ "url": "https://github.com/tillafrica/tilldev/issues"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "build": "tsup",
49
+ "dev": "tsup --watch",
50
+ "typecheck": "tsc --noEmit",
51
+ "clean": "rm -rf dist"
52
+ }
53
+ }