@tensile-tools/auth 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +142 -2
- package/dist/adapt.d.ts +54 -0
- package/dist/adapt.js +72 -0
- package/dist/api.d.ts +63 -0
- package/dist/api.js +8 -0
- package/dist/body.d.ts +18 -0
- package/dist/body.js +55 -0
- package/dist/cache.d.ts +73 -0
- package/dist/cache.js +222 -0
- package/dist/clientip.d.ts +43 -0
- package/dist/clientip.js +151 -0
- package/dist/core.d.ts +219 -0
- package/dist/core.js +420 -0
- package/dist/express.d.ts +60 -0
- package/dist/express.js +110 -0
- package/dist/gen/api.d.ts +5368 -0
- package/dist/gen/api.js +5 -0
- package/dist/hono.d.ts +49 -0
- package/dist/hono.js +43 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -0
- package/dist/next.d.ts +106 -0
- package/dist/next.js +205 -0
- package/dist/problem.d.ts +36 -0
- package/dist/problem.js +79 -0
- package/dist/proxy.d.ts +57 -0
- package/dist/proxy.js +137 -0
- package/dist/rebuild.d.ts +19 -0
- package/dist/rebuild.js +48 -0
- package/dist/transport.d.ts +6 -0
- package/dist/transport.js +39 -0
- package/dist/webhooks.d.ts +53 -0
- package/dist/webhooks.js +124 -0
- package/express/README.md +62 -0
- package/hono/README.md +58 -0
- package/next/README.md +89 -0
- package/package.json +100 -4
package/dist/proxy.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// The proxy: a Fetch API handler that forwards the browser routes to the
|
|
2
|
+
// server, so sessions stay in __Host- cookies on the app's own origin.
|
|
3
|
+
import { maxBody } from "./body.js";
|
|
4
|
+
import { serverURL } from "./transport.js";
|
|
5
|
+
import { problem, problemResponse, unavailable } from "./problem.js";
|
|
6
|
+
/** The library's cookies: the only ones the proxy forwards, in either direction. */
|
|
7
|
+
export const libraryCookies = new Set(['__Host-session', '__Host-pending', '__Host-signup', '__Host-known', '__Host-reset']);
|
|
8
|
+
/** The largest request body the proxy forwards: 1 MiB. */
|
|
9
|
+
export const maxRequestBody = maxBody;
|
|
10
|
+
const requestHeaders = new Set([
|
|
11
|
+
'origin', 'sec-fetch-site', 'sec-fetch-mode', 'user-agent', 'content-type', 'accept', 'authorization', 'dpop',
|
|
12
|
+
// DBSC sends its session ID with the Sec- prefix.
|
|
13
|
+
'sec-secure-session-id',
|
|
14
|
+
]);
|
|
15
|
+
const responseHeaders = new Set([
|
|
16
|
+
'cache-control', 'www-authenticate', 'retry-after', 'tensile-auth-fresh-until', 'tensile-auth-assurance',
|
|
17
|
+
'content-type', 'location',
|
|
18
|
+
// Security headers of the pages the server serves, which dropping would weaken.
|
|
19
|
+
'content-security-policy', 'x-content-type-options', 'x-frame-options', 'referrer-policy',
|
|
20
|
+
]);
|
|
21
|
+
const secureSession = /^secure-session-/;
|
|
22
|
+
/** The path prefixes the proxy forwards for `routes`. */
|
|
23
|
+
export function proxyPrefixes(routes = {}) {
|
|
24
|
+
const p = ['/auth/'];
|
|
25
|
+
if (routes.admin)
|
|
26
|
+
p.push('/admin/');
|
|
27
|
+
if (routes.oauth)
|
|
28
|
+
p.push('/login/oauth/');
|
|
29
|
+
if (routes.device)
|
|
30
|
+
p.push('/login/device/');
|
|
31
|
+
if (routes.wellKnown)
|
|
32
|
+
p.push('/.well-known/');
|
|
33
|
+
return p;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reports whether the proxy forwards `pathname`, which must be the raw,
|
|
37
|
+
* still-encoded path. Encoded dots, slashes, and backslashes, and empty
|
|
38
|
+
* segments, are refused, so no path reaches a route outside the prefixes
|
|
39
|
+
* after the server decodes it.
|
|
40
|
+
*/
|
|
41
|
+
export function isProxied(pathname, routes = {}) {
|
|
42
|
+
if (/%2e|%2f|%5c|\\|\/\//i.test(pathname))
|
|
43
|
+
return false;
|
|
44
|
+
if (pathname.split('/').some(s => s === '.' || s === '..'))
|
|
45
|
+
return false;
|
|
46
|
+
return proxyPrefixes(routes).some(p => pathname.startsWith(p));
|
|
47
|
+
}
|
|
48
|
+
/** Keeps only the library's cookies in a `Cookie` header. */
|
|
49
|
+
export function filterCookieHeader(header) {
|
|
50
|
+
if (!header)
|
|
51
|
+
return undefined;
|
|
52
|
+
const kept = header.split(';').map(s => s.trim()).filter(s => libraryCookies.has(s.slice(0, s.indexOf('='))));
|
|
53
|
+
return kept.length ? kept.join('; ') : undefined;
|
|
54
|
+
}
|
|
55
|
+
/** Reports whether a `Set-Cookie` value sets one of the library's cookies. */
|
|
56
|
+
export function isLibrarySetCookie(value) {
|
|
57
|
+
return libraryCookies.has(value.slice(0, value.indexOf('=')).trim());
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Creates the proxy. It forwards allowlisted paths with the library's
|
|
61
|
+
* cookies and a fixed set of headers, adds the app key and the client's
|
|
62
|
+
* address, and returns the server's status, body, and allowlisted
|
|
63
|
+
* headers. Any other path answers 404 without reaching the server.
|
|
64
|
+
*/
|
|
65
|
+
export function createProxy(o) {
|
|
66
|
+
const base = serverURL(o.url);
|
|
67
|
+
const fetchFn = o.fetch ?? globalThis.fetch.bind(globalThis);
|
|
68
|
+
const timeoutMs = o.timeoutMs ?? 30_000;
|
|
69
|
+
const claimTimeoutMs = o.claimTimeoutMs ?? 65_000;
|
|
70
|
+
const notFound = () => problemResponse(problem(404, 'not_found', 'Not found'));
|
|
71
|
+
return async (req, ctx = {}) => {
|
|
72
|
+
const incoming = new URL(req.url);
|
|
73
|
+
if (!isProxied(incoming.pathname, o))
|
|
74
|
+
return notFound();
|
|
75
|
+
const headers = new Headers();
|
|
76
|
+
req.headers.forEach((v, k) => {
|
|
77
|
+
if (requestHeaders.has(k) || secureSession.test(k))
|
|
78
|
+
headers.set(k, v);
|
|
79
|
+
});
|
|
80
|
+
const cookie = filterCookieHeader(req.headers.get('cookie'));
|
|
81
|
+
if (cookie)
|
|
82
|
+
headers.set('cookie', cookie);
|
|
83
|
+
headers.set('tensile-app-key', o.appKey);
|
|
84
|
+
if (ctx.clientIp)
|
|
85
|
+
headers.set('tensile-client-ip', ctx.clientIp);
|
|
86
|
+
let body;
|
|
87
|
+
let tooLarge = false;
|
|
88
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && req.body) {
|
|
89
|
+
const declared = Number(req.headers.get('content-length'));
|
|
90
|
+
if (declared > maxRequestBody)
|
|
91
|
+
return problemResponse(problem(413, 'body_too_large', 'The request is too large'));
|
|
92
|
+
let seen = 0;
|
|
93
|
+
body = req.body.pipeThrough(new TransformStream({
|
|
94
|
+
transform(chunk, c) {
|
|
95
|
+
seen += chunk.byteLength;
|
|
96
|
+
if (seen > maxRequestBody) {
|
|
97
|
+
tooLarge = true;
|
|
98
|
+
c.error(new RangeError('request body is larger than 1 MiB'));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
c.enqueue(chunk);
|
|
102
|
+
},
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
const target = new URL(incoming.pathname + incoming.search, base);
|
|
106
|
+
let res;
|
|
107
|
+
try {
|
|
108
|
+
res = await fetchFn(target, {
|
|
109
|
+
method: req.method,
|
|
110
|
+
headers,
|
|
111
|
+
body,
|
|
112
|
+
redirect: 'manual',
|
|
113
|
+
signal: AbortSignal.timeout(incoming.pathname.startsWith('/auth/claims/') ? claimTimeoutMs : timeoutMs),
|
|
114
|
+
...(body ? { duplex: 'half' } : {}),
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
if (tooLarge)
|
|
119
|
+
return problemResponse(problem(413, 'body_too_large', 'The request is too large'));
|
|
120
|
+
return problemResponse(unavailable);
|
|
121
|
+
}
|
|
122
|
+
if (tooLarge) {
|
|
123
|
+
await res.body?.cancel();
|
|
124
|
+
return problemResponse(problem(413, 'body_too_large', 'The request is too large'));
|
|
125
|
+
}
|
|
126
|
+
const out = new Headers();
|
|
127
|
+
res.headers.forEach((v, k) => {
|
|
128
|
+
if (k !== 'set-cookie' && (responseHeaders.has(k) || secureSession.test(k)))
|
|
129
|
+
out.set(k, v);
|
|
130
|
+
});
|
|
131
|
+
for (const c of res.headers.getSetCookie())
|
|
132
|
+
if (isLibrarySetCookie(c))
|
|
133
|
+
out.append('set-cookie', c);
|
|
134
|
+
const empty = req.method === 'HEAD' || res.status === 204 || res.status === 304;
|
|
135
|
+
return new Response(empty ? null : res.body, { status: res.status, statusText: res.statusText, headers: out });
|
|
136
|
+
};
|
|
137
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The header `gate` sets with the page's path and query. */
|
|
2
|
+
export declare const pathHeader = "x-tensile-path";
|
|
3
|
+
/** The header `gate` sets with the request's method and this process's token. */
|
|
4
|
+
export declare const methodHeader = "x-tensile-method";
|
|
5
|
+
/** The value of `methodHeader` that attests `method`. */
|
|
6
|
+
export declare function attestMethod(method: string): string;
|
|
7
|
+
/**
|
|
8
|
+
* The method of the request behind `h`: the attested one when `gate` set
|
|
9
|
+
* a valid attestation, and otherwise POST, because without it a page
|
|
10
|
+
* render can't be told from a Server Action or a form post.
|
|
11
|
+
*/
|
|
12
|
+
export declare function methodOf(h: Headers): string;
|
|
13
|
+
/**
|
|
14
|
+
* Rebuilds the request from its headers: the method from `methodOf`, the
|
|
15
|
+
* path from `pathHeader`, and the origin from `appUrl` or the `Host`
|
|
16
|
+
* header. Its headers keep `Origin` and `Sec-Fetch-Site`, so the check
|
|
17
|
+
* applies cross-origin protection to it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function rebuildRequest(h: Headers, appUrl?: string): Request;
|
package/dist/rebuild.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Rebuilding the request a Server Component or Server Action serves.
|
|
2
|
+
//
|
|
3
|
+
// Next.js gives them the request's headers, but not its method or URL.
|
|
4
|
+
// The check must know the method: cross-origin protection applies to
|
|
5
|
+
// unsafe methods only, and a Server Action is a POST. So a rebuilt request
|
|
6
|
+
// is unsafe (POST) unless `gate` in proxy.ts, which sees the real request,
|
|
7
|
+
// attests its method. The attestation carries a random token that lives
|
|
8
|
+
// only in this process, so a client can't forge it.
|
|
9
|
+
/** The header `gate` sets with the page's path and query. */
|
|
10
|
+
export const pathHeader = 'x-tensile-path';
|
|
11
|
+
/** The header `gate` sets with the request's method and this process's token. */
|
|
12
|
+
export const methodHeader = 'x-tensile-method';
|
|
13
|
+
const tokenKey = Symbol.for('tensile.auth.gate-token');
|
|
14
|
+
// gateToken is shared by every copy of this module in the process, so
|
|
15
|
+
// proxy.ts and the pages, which Next.js bundles apart, agree on it.
|
|
16
|
+
function gateToken() {
|
|
17
|
+
const g = globalThis;
|
|
18
|
+
return (g[tokenKey] ??= crypto.randomUUID());
|
|
19
|
+
}
|
|
20
|
+
/** The value of `methodHeader` that attests `method`. */
|
|
21
|
+
export function attestMethod(method) {
|
|
22
|
+
return `${method.toUpperCase()} ${gateToken()}`;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The method of the request behind `h`: the attested one when `gate` set
|
|
26
|
+
* a valid attestation, and otherwise POST, because without it a page
|
|
27
|
+
* render can't be told from a Server Action or a form post.
|
|
28
|
+
*/
|
|
29
|
+
export function methodOf(h) {
|
|
30
|
+
const attested = h.get(methodHeader);
|
|
31
|
+
if (attested && !h.has('next-action')) {
|
|
32
|
+
const [method, token] = attested.split(' ');
|
|
33
|
+
if (token === gateToken() && /^[A-Z]+$/.test(method))
|
|
34
|
+
return method;
|
|
35
|
+
}
|
|
36
|
+
return 'POST';
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Rebuilds the request from its headers: the method from `methodOf`, the
|
|
40
|
+
* path from `pathHeader`, and the origin from `appUrl` or the `Host`
|
|
41
|
+
* header. Its headers keep `Origin` and `Sec-Fetch-Site`, so the check
|
|
42
|
+
* applies cross-origin protection to it.
|
|
43
|
+
*/
|
|
44
|
+
export function rebuildRequest(h, appUrl) {
|
|
45
|
+
const path = h.get(pathHeader);
|
|
46
|
+
const origin = appUrl ?? `${h.get('x-forwarded-proto')?.split(',')[0] ?? 'http'}://${h.get('x-forwarded-host') ?? h.get('host')}`;
|
|
47
|
+
return new Request(new URL(path?.startsWith('/') && !path.startsWith('//') ? path : '/', origin), { method: methodOf(h), headers: h });
|
|
48
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Transport safety: which server URLs the SDK talks to.
|
|
2
|
+
/**
|
|
3
|
+
* Parses and checks the server URL. `http://` is allowed only for
|
|
4
|
+
* loopback hosts, private addresses, and single-label names such as
|
|
5
|
+
* `tensile-auth` on a Compose network.
|
|
6
|
+
*/
|
|
7
|
+
export function serverURL(raw) {
|
|
8
|
+
let u;
|
|
9
|
+
try {
|
|
10
|
+
u = new URL(raw);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw new TypeError(`tensile: url ${JSON.stringify(raw)} isn't a URL`);
|
|
14
|
+
}
|
|
15
|
+
if (u.username || u.password)
|
|
16
|
+
throw new TypeError('tensile: url must not hold credentials');
|
|
17
|
+
if (u.protocol === 'https:')
|
|
18
|
+
return u;
|
|
19
|
+
if (u.protocol !== 'http:')
|
|
20
|
+
throw new TypeError(`tensile: url must be https:// or http://, not ${u.protocol}`);
|
|
21
|
+
if (!plainHTTPAllowed(u.hostname)) {
|
|
22
|
+
throw new TypeError(`tensile: url ${u.origin} uses http:// on a public host; use https://, or a loopback, private, or single-label host`);
|
|
23
|
+
}
|
|
24
|
+
return u;
|
|
25
|
+
}
|
|
26
|
+
function plainHTTPAllowed(host) {
|
|
27
|
+
const h = host.replace(/^\[|\]$/g, '').toLowerCase();
|
|
28
|
+
if (h === 'localhost' || h.endsWith('.localhost'))
|
|
29
|
+
return true;
|
|
30
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
|
|
31
|
+
if (v4) {
|
|
32
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
33
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
34
|
+
}
|
|
35
|
+
if (h.includes(':')) {
|
|
36
|
+
return h === '::1' || /^f[cd][0-9a-f]{2}:/.test(h) || /^fe[89ab][0-9a-f]:/.test(h);
|
|
37
|
+
}
|
|
38
|
+
return !h.includes('.');
|
|
39
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** A verified webhook or hook. */
|
|
2
|
+
export interface WebhookEvent<T = Record<string, unknown>> {
|
|
3
|
+
/** The `webhook-id`, the same on every delivery of one event. Use it to drop duplicates. */
|
|
4
|
+
id: string;
|
|
5
|
+
/** When the server signed it. */
|
|
6
|
+
timestamp: Date;
|
|
7
|
+
/** The event type, for example `user.created` or `sign_up`. */
|
|
8
|
+
type: string;
|
|
9
|
+
/** The parsed body. */
|
|
10
|
+
payload: T;
|
|
11
|
+
}
|
|
12
|
+
/** Options of `verifyWebhook`. */
|
|
13
|
+
export interface WebhookOptions {
|
|
14
|
+
/** The signing secret, `whsec_…` followed by base64, or several while one rotates. */
|
|
15
|
+
secret: string | string[];
|
|
16
|
+
/** The most a timestamp may differ from now, in seconds. Defaults to 300. */
|
|
17
|
+
toleranceSeconds?: number;
|
|
18
|
+
/** The current time, for tests. */
|
|
19
|
+
now?: () => Date;
|
|
20
|
+
}
|
|
21
|
+
/** Why a webhook was refused. Answer it with 400 and don't act on it. */
|
|
22
|
+
export declare class WebhookError extends Error {
|
|
23
|
+
constructor(message: string);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Checks a request's Standard Webhooks signature against each secret and
|
|
27
|
+
* returns its event. It refuses a missing or wrong signature, and a
|
|
28
|
+
* timestamp more than `toleranceSeconds` from now in either direction.
|
|
29
|
+
*/
|
|
30
|
+
export declare function verifyWebhook(request: Request, o: WebhookOptions): Promise<WebhookEvent>;
|
|
31
|
+
/** The answer to a hook: `{allow, user_id?}` to `sign_up`, `{scopes}` to `session_scopes`. */
|
|
32
|
+
export type HookAnswer = {
|
|
33
|
+
allow: boolean;
|
|
34
|
+
user_id?: string;
|
|
35
|
+
} | {
|
|
36
|
+
scopes: string[];
|
|
37
|
+
};
|
|
38
|
+
/** Options of `answerHook`. */
|
|
39
|
+
export interface HookAnswerOptions {
|
|
40
|
+
/** The signing secret, or several while one rotates: the answer carries a signature for each. */
|
|
41
|
+
secret: string | string[];
|
|
42
|
+
/** The current time, for tests. */
|
|
43
|
+
now?: () => Date;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Answers a hook. The server reads an answer only when it is signed for
|
|
47
|
+
* the hook's own `webhook-id`, with a timestamp within 5 minutes and a
|
|
48
|
+
* live secret, so a recorded answer can't be replayed for another
|
|
49
|
+
* sign-up. Pass the event that `verifyWebhook` returned.
|
|
50
|
+
*/
|
|
51
|
+
export declare function answerHook(event: Pick<WebhookEvent, 'id'>, answer: HookAnswer, o: HookAnswerOptions): Promise<Response>;
|
|
52
|
+
/** Signs a body as the server does, for tests: returns the three `webhook-*` headers. */
|
|
53
|
+
export declare function signWebhook(secret: string, id: string, timestamp: Date, body: string): Promise<Record<string, string>>;
|
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Standard Webhooks verification (https://www.standardwebhooks.com/):
|
|
2
|
+
// HMAC-SHA256 over the ID, timestamp, and body, with Web Crypto only.
|
|
3
|
+
import { BodyTooLargeError, maxBody, readBytes } from "./body.js";
|
|
4
|
+
/** Why a webhook was refused. Answer it with 400 and don't act on it. */
|
|
5
|
+
export class WebhookError extends Error {
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'WebhookError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Checks a request's Standard Webhooks signature against each secret and
|
|
13
|
+
* returns its event. It refuses a missing or wrong signature, and a
|
|
14
|
+
* timestamp more than `toleranceSeconds` from now in either direction.
|
|
15
|
+
*/
|
|
16
|
+
export async function verifyWebhook(request, o) {
|
|
17
|
+
const id = request.headers.get('webhook-id');
|
|
18
|
+
const ts = request.headers.get('webhook-timestamp');
|
|
19
|
+
const sigs = request.headers.get('webhook-signature');
|
|
20
|
+
if (!id || !ts || !sigs)
|
|
21
|
+
throw new WebhookError('webhook: missing webhook-id, webhook-timestamp, or webhook-signature');
|
|
22
|
+
if (!/^\d{1,12}$/.test(ts))
|
|
23
|
+
throw new WebhookError('webhook: webhook-timestamp is not a number of seconds');
|
|
24
|
+
const now = Math.floor((o.now?.() ?? new Date()).getTime() / 1000);
|
|
25
|
+
const tolerance = o.toleranceSeconds ?? 300;
|
|
26
|
+
if (Math.abs(now - Number(ts)) > tolerance)
|
|
27
|
+
throw new WebhookError('webhook: the timestamp is too old or in the future');
|
|
28
|
+
// The body is read only after the headers pass, at most 1 MiB of it,
|
|
29
|
+
// and the signature is checked over its exact bytes.
|
|
30
|
+
let raw;
|
|
31
|
+
try {
|
|
32
|
+
raw = await readBytes(request, maxBody);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
if (err instanceof BodyTooLargeError)
|
|
36
|
+
throw new WebhookError('webhook: the body is larger than 1 MiB');
|
|
37
|
+
throw new WebhookError('webhook: the body could not be read');
|
|
38
|
+
}
|
|
39
|
+
const prefix = new TextEncoder().encode(`${id}.${ts}.`);
|
|
40
|
+
const signed = new Uint8Array(prefix.byteLength + raw.byteLength);
|
|
41
|
+
signed.set(prefix);
|
|
42
|
+
signed.set(raw, prefix.byteLength);
|
|
43
|
+
const offered = sigs.split(' ').flatMap(s => {
|
|
44
|
+
const [version, value] = s.split(',', 2);
|
|
45
|
+
return version === 'v1' && value ? [decodeBase64(value)] : [];
|
|
46
|
+
}).filter((b) => b !== undefined);
|
|
47
|
+
let ok = false;
|
|
48
|
+
for (const secret of Array.isArray(o.secret) ? o.secret : [o.secret]) {
|
|
49
|
+
const want = await sign(secret, signed);
|
|
50
|
+
for (const got of offered)
|
|
51
|
+
ok = equal(want, got) || ok;
|
|
52
|
+
}
|
|
53
|
+
if (!ok)
|
|
54
|
+
throw new WebhookError('webhook: no signature matches');
|
|
55
|
+
let payload;
|
|
56
|
+
try {
|
|
57
|
+
payload = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
throw new WebhookError('webhook: the body is not JSON');
|
|
61
|
+
}
|
|
62
|
+
return { id, timestamp: new Date(Number(ts) * 1000), type: String(payload.type ?? ''), payload };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Answers a hook. The server reads an answer only when it is signed for
|
|
66
|
+
* the hook's own `webhook-id`, with a timestamp within 5 minutes and a
|
|
67
|
+
* live secret, so a recorded answer can't be replayed for another
|
|
68
|
+
* sign-up. Pass the event that `verifyWebhook` returned.
|
|
69
|
+
*/
|
|
70
|
+
export async function answerHook(event, answer, o) {
|
|
71
|
+
if (!event.id)
|
|
72
|
+
throw new TypeError('webhook: answer a hook with the event verifyWebhook returned, which carries its webhook-id');
|
|
73
|
+
const body = JSON.stringify(answer);
|
|
74
|
+
const ts = String(Math.floor((o.now?.() ?? new Date()).getTime() / 1000));
|
|
75
|
+
const data = new TextEncoder().encode(`${event.id}.${ts}.${body}`);
|
|
76
|
+
const sigs = [];
|
|
77
|
+
for (const secret of Array.isArray(o.secret) ? o.secret : [o.secret])
|
|
78
|
+
sigs.push(`v1,${encodeBase64(await sign(secret, data))}`);
|
|
79
|
+
if (!sigs.length)
|
|
80
|
+
throw new TypeError('webhook: answerHook needs a secret');
|
|
81
|
+
return new Response(body, {
|
|
82
|
+
headers: {
|
|
83
|
+
'content-type': 'application/json', 'cache-control': 'no-store',
|
|
84
|
+
'webhook-id': event.id, 'webhook-timestamp': ts, 'webhook-signature': sigs.join(' '),
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** Signs a body as the server does, for tests: returns the three `webhook-*` headers. */
|
|
89
|
+
export async function signWebhook(secret, id, timestamp, body) {
|
|
90
|
+
const ts = String(Math.floor(timestamp.getTime() / 1000));
|
|
91
|
+
const sig = await sign(secret, new TextEncoder().encode(`${id}.${ts}.${body}`));
|
|
92
|
+
return { 'webhook-id': id, 'webhook-timestamp': ts, 'webhook-signature': `v1,${encodeBase64(sig)}` };
|
|
93
|
+
}
|
|
94
|
+
async function sign(secret, data) {
|
|
95
|
+
const raw = decodeBase64(secret.startsWith('whsec_') ? secret.slice(6) : secret);
|
|
96
|
+
if (!raw || raw.length < 16)
|
|
97
|
+
throw new TypeError('webhook: the secret must be whsec_ followed by at least 16 bytes of base64');
|
|
98
|
+
const key = await crypto.subtle.importKey('raw', raw, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
99
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', key, data));
|
|
100
|
+
}
|
|
101
|
+
// equal compares in time that depends only on the lengths.
|
|
102
|
+
function equal(a, b) {
|
|
103
|
+
if (a.length !== b.length)
|
|
104
|
+
return false;
|
|
105
|
+
let d = 0;
|
|
106
|
+
for (let i = 0; i < a.length; i++)
|
|
107
|
+
d |= a[i] ^ b[i];
|
|
108
|
+
return d === 0;
|
|
109
|
+
}
|
|
110
|
+
function decodeBase64(s) {
|
|
111
|
+
try {
|
|
112
|
+
const bin = atob(s);
|
|
113
|
+
return Uint8Array.from(bin, c => c.charCodeAt(0));
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function encodeBase64(b) {
|
|
120
|
+
let bin = '';
|
|
121
|
+
for (const x of b)
|
|
122
|
+
bin += String.fromCharCode(x);
|
|
123
|
+
return btoa(bin);
|
|
124
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# @tensile-tools/auth/express
|
|
2
|
+
|
|
3
|
+
The Express 5 adapter of `@tensile-tools/auth`. Express is a peer dependency: the app installs it.
|
|
4
|
+
|
|
5
|
+
## Use it
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import express from 'express'
|
|
9
|
+
import { tensile } from '@tensile-tools/auth/express'
|
|
10
|
+
|
|
11
|
+
const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
|
|
12
|
+
const app = express()
|
|
13
|
+
|
|
14
|
+
app.use(auth.proxy()) // before any body parser
|
|
15
|
+
app.use(express.json())
|
|
16
|
+
|
|
17
|
+
app.get('/me', auth.authenticate(), (req, res) => res.json({ user: req.principal?.user ?? null }))
|
|
18
|
+
|
|
19
|
+
app.delete('/repos/:id',
|
|
20
|
+
auth.approvable({ action: 'repo.delete', human: true, scopes: ['repo:admin'] },
|
|
21
|
+
req => ({ kind: 'repo.delete', resource: req.params.id, summary: `Delete the repository ${req.params.id}` })),
|
|
22
|
+
async (req, res) => { await repos.delete(req.params.id, req.principal!.user); res.sendStatus(204) })
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| Part | What it does |
|
|
26
|
+
|---|---|
|
|
27
|
+
| `auth.proxy(routes?)` | Forwards `/auth/` to the server, and `/admin/`, `/login/oauth/`, `/login/device/`, and `/.well-known/` when `routes` turns them on. Other paths go to the next handler. Mount it before body parsers, because it streams the request body |
|
|
28
|
+
| `auth.authenticate()` | Sets `req.principal`, or leaves it `undefined` when the request carries no credential or a session cookie the server no longer knows. A bad bearer token gets a 401 problem |
|
|
29
|
+
| `auth.need(need)` | Lets the request through only when the principal meets `need`, for example `{action: 'settings.edit', human: true, within: '10m'}`. Otherwise answers the server's problem |
|
|
30
|
+
| `auth.approvable(need, describe, options?)` | Like `need`. When an agent meets a human-only need, the server creates an approval for the action `describe(req)` returns and answers `human_required` with `challenge.approval`. The agent retries with `Tensile-Approval: apr_…`, which redeems it once. With `Prefer: wait=N` on the retry, the route holds it until the person decides, for at most `approvalWait` seconds, or `options.wait` for this route; see [wait for an approval](../README.md#wait-for-an-approval). The wait ends when the client disconnects |
|
|
31
|
+
| `auth.as(req)` | Calls on the person's behalf with the request's credential, for example `auth.as(req).agents.create({name, scopes})`. A refusal throws a `ProblemError`; answer it with `err.toResponse()` or its `problem` |
|
|
32
|
+
| `auth.client` | The core client from `createTensile` |
|
|
33
|
+
|
|
34
|
+
Every response copies the server's cookies and the `Tensile-Auth-Fresh-Until` header, so cookie rotation and step-up timers work. When the server can't decide, the adapter answers 503, never 401.
|
|
35
|
+
|
|
36
|
+
## The client's address
|
|
37
|
+
|
|
38
|
+
The server uses the client's address for rate limits and the audit log. Anyone who connects to the app directly can send `X-Forwarded-For` and `X-Real-IP`, so the adapter reads a forwarded header only when you name it in `trustProxy` and the socket's address is in `trustedProxies`, as `authhttp.WithClientIP` does:
|
|
39
|
+
|
|
40
|
+
| `trustProxy` | The header the adapter reads |
|
|
41
|
+
|---|---|
|
|
42
|
+
| Unset or `false` | None |
|
|
43
|
+
| `{ header: 'x-forwarded-for', hops: n }` | The `n`th `X-Forwarded-For` entry from the right, for `n` proxies in a chain |
|
|
44
|
+
| `{ header: 'x-real-ip' }` | `X-Real-IP`, for a proxy that sets it |
|
|
45
|
+
| `true` | Shorthand for `x-forwarded-for` with 1 hop |
|
|
46
|
+
| A number `n` | Shorthand for `x-forwarded-for` with `n` hops |
|
|
47
|
+
|
|
48
|
+
The adapter reads only the header named. It never falls back from one header to the other, so a client-sent `X-Forwarded-For` can't override the `X-Real-IP` your proxy sets.
|
|
49
|
+
|
|
50
|
+
`trustedProxies` lists your proxies' own addresses as CIDRs, for example `['10.0.0.0/8', 'fd00::/8']`. It defaults to none. Without a match, the adapter sends the socket's address, so `trustProxy` alone has no effect. Express's own `trust proxy` setting isn't consulted.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const auth = tensile({ /* ... */ trustProxy: true, trustedProxies: ['10.0.0.0/8'] })
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
When you set `trustedProxies`, the walk along `X-Forwarded-For` also stops at the first entry outside them, and an entry that isn't an IP address stops it too, as in `authhttp`. A configuration that isn't valid, such as `hops: 0` or a malformed CIDR, throws when you create the adapter.
|
|
57
|
+
|
|
58
|
+
To read the address another way, pass `clientIp`, which overrides both options.
|
|
59
|
+
|
|
60
|
+
## See also
|
|
61
|
+
|
|
62
|
+
- [The SDK](../README.md)
|
package/hono/README.md
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# @tensile-tools/auth/hono
|
|
2
|
+
|
|
3
|
+
The Hono 4 adapter of `@tensile-tools/auth`. Hono is a peer dependency: the app installs it.
|
|
4
|
+
|
|
5
|
+
## Use it
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Hono } from 'hono'
|
|
9
|
+
import { tensile, type TensileEnv } from '@tensile-tools/auth/hono'
|
|
10
|
+
|
|
11
|
+
const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
|
|
12
|
+
const app = new Hono<TensileEnv>()
|
|
13
|
+
|
|
14
|
+
app.all('/auth/*', auth.proxy())
|
|
15
|
+
app.get('/me', auth.authenticate(), c => c.json({ user: c.get('principal')?.user ?? null }))
|
|
16
|
+
app.delete('/repos/:id',
|
|
17
|
+
auth.approvable({ action: 'repo.delete', human: true },
|
|
18
|
+
c => ({ kind: 'repo.delete', resource: c.req.param('id')!, summary: `Delete the repository ${c.req.param('id')}` })),
|
|
19
|
+
c => c.body(null, 204))
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
| Part | What it does |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `auth.proxy(routes?)` | A handler that forwards the browser routes to the server. Mount it at `/auth/*`, and at `/admin/*`, `/login/oauth/*`, `/login/device/*`, or `/.well-known/*` with the matching `routes` option. Any path outside them answers 404 |
|
|
25
|
+
| `auth.authenticate()` | Sets `c.get('principal')`, or leaves it `undefined` when the request carries no credential or a session cookie the server no longer knows. A bad bearer token gets a 401 problem |
|
|
26
|
+
| `auth.need(need)` | Lets the request through only when the principal meets `need`. Otherwise answers the server's problem |
|
|
27
|
+
| `auth.approvable(need, describe, options?)` | Like `need`, and an agent may ask its human to approve the action `describe(c)` returns, then retry with `Tensile-Approval`. With `Prefer: wait=N` on the retry, the route holds it until the person decides, for at most `approvalWait` seconds, or `options.wait` for this route; see [wait for an approval](../README.md#wait-for-an-approval). The wait ends when `c.req.raw.signal` aborts. On Cloudflare Workers, Deno Deploy, and other edge runtimes, `approvalWait` defaults to 0 |
|
|
28
|
+
| `auth.as(c)` | Calls on the person's behalf with the request's credential. A refusal throws a `ProblemError`; return `err.toResponse()` |
|
|
29
|
+
| `auth.client` | The core client from `createTensile` |
|
|
30
|
+
|
|
31
|
+
## The client's address
|
|
32
|
+
|
|
33
|
+
The server uses the client's address for rate limits and the audit log. Anyone who connects to the app directly can send `X-Forwarded-For` and `X-Real-IP`, so the adapter reads a forwarded header only when you name it in `trustProxy` and, where the socket's address is known, that address is in `trustedProxies`, as `authhttp.WithClientIP` does:
|
|
34
|
+
|
|
35
|
+
| `trustProxy` | The header the adapter reads |
|
|
36
|
+
|---|---|
|
|
37
|
+
| Unset or `false` | None |
|
|
38
|
+
| `{ header: 'x-forwarded-for', hops: n }` | The `n`th `X-Forwarded-For` entry from the right, for `n` proxies in a chain |
|
|
39
|
+
| `{ header: 'x-real-ip' }` | `X-Real-IP`, for a proxy that sets it |
|
|
40
|
+
| `true` | Shorthand for `x-forwarded-for` with 1 hop |
|
|
41
|
+
| A number `n` | Shorthand for `x-forwarded-for` with `n` hops |
|
|
42
|
+
|
|
43
|
+
The adapter reads only the header named. It never falls back from one header to the other, so a client-sent `X-Forwarded-For` can't override the `X-Real-IP` your proxy sets.
|
|
44
|
+
|
|
45
|
+
`trustedProxies` lists your proxies' own addresses as CIDRs, for example `['10.0.0.0/8', 'fd00::/8']`. It defaults to none.
|
|
46
|
+
|
|
47
|
+
- Under `@hono/node-server` or Bun, the adapter knows the socket's address. It reads the header only when that address is in `trustedProxies`, and sends the socket's address otherwise, so `trustProxy` alone has no effect.
|
|
48
|
+
- On runtimes that expose no socket address, such as Deno Deploy or Cloudflare Workers, the adapter sends no address without `trustProxy`, and reads the header on every request with it. Set `trustProxy` there only when the platform overwrites that header on every request.
|
|
49
|
+
|
|
50
|
+
When you set `trustedProxies`, the walk along `X-Forwarded-For` also stops at the first entry outside them, and an entry that isn't an IP address stops it too, as in `authhttp`. A configuration that isn't valid, such as `hops: 0` or a malformed CIDR, throws when you create the adapter.
|
|
51
|
+
|
|
52
|
+
To read the address another way, pass `clientIp`, which overrides both options.
|
|
53
|
+
|
|
54
|
+
The adapter's tests pass on Node and on Deno 2.9. Bun isn't tested yet.
|
|
55
|
+
|
|
56
|
+
## See also
|
|
57
|
+
|
|
58
|
+
- [The SDK](../README.md)
|
package/next/README.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# @tensile-tools/auth/next
|
|
2
|
+
|
|
3
|
+
The Next.js adapter of `@tensile-tools/auth`, for the App Router on the Node.js runtime. Next.js 16 or later is a peer dependency: the app installs it.
|
|
4
|
+
|
|
5
|
+
## Use it
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// lib/auth.ts
|
|
9
|
+
import { tensile } from '@tensile-tools/auth/next'
|
|
10
|
+
export const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY!, signIn: '/sign-in' })
|
|
11
|
+
|
|
12
|
+
// app/auth/[...path]/route.ts
|
|
13
|
+
import { auth } from '@/lib/auth'
|
|
14
|
+
export const { GET, POST } = auth.proxy
|
|
15
|
+
|
|
16
|
+
// app/settings/page.tsx (imports auth the same way)
|
|
17
|
+
export default async function Settings() {
|
|
18
|
+
const p = await auth.require({ action: 'settings.view', human: true })
|
|
19
|
+
return <SettingsForm user={await db.user.findUniqueOrThrow({ where: { authUserId: p.user } })} />
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
| Part | What it does |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `auth.proxy` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS` handlers that forward the browser routes. Export them from `app/auth/[...path]/route.ts`. To forward `/admin/` or the OAuth routes, set `routes` and add the matching catch-all route |
|
|
26
|
+
| `auth.principal()` | The principal, or `undefined` when signed out. Works in Server Components, Server Actions, and route handlers |
|
|
27
|
+
| `auth.require(need?)` | The principal, when it meets `need`. Otherwise a page or Server Action redirects to `signIn` for a 401, or to `stepUp` for a step-up challenge, with `?next=` set to the page. Other refusals throw a `ProblemError`, which the nearest error boundary renders. Inside `auth.route`, every refusal becomes a problem response instead |
|
|
28
|
+
| `auth.route(handler)` | Wraps a route handler, so that `require` inside it answers problems, and the server's cookies reach its response |
|
|
29
|
+
| `auth.approvable(need, describe, handler, options?)` | A route handler that an agent may ask its human to approve. `handler` gets `ctx.principal`. With `Prefer: wait=N` on the retry, it holds the request until the person decides, for at most `approvalWait` seconds, or `options.wait` for this route, and ends the wait when `req.signal` aborts |
|
|
30
|
+
| `auth.subject()`, `auth.as(subject)` | Calls on the person's behalf: `auth.as(await auth.subject()).agents.create({name, scopes})` |
|
|
31
|
+
| `auth.gate(options?)` | A `proxy.ts` function that attests each request's method to the pages, carries rotated cookies, and redirects signed-out navigations to `signIn` early. It never replaces `require`, because it can't see which need a page declares |
|
|
32
|
+
|
|
33
|
+
Options of `tensile`, beyond the core's: `signIn` (required), `stepUp` (defaults to `signIn`), `appUrl` (defaults to the request's host), `routes`, `trustProxy`, `trustedProxies`, and `clientIp`.
|
|
34
|
+
|
|
35
|
+
On Vercel, `approvalWait` defaults to 0, so an agent's retry answers at once and the agent retries after `Retry-After`. To hold it for the person's tap, set the wait and the function's limit together, with `maxDuration >= approvalWait + 5`:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// app/api/repos/[id]/route.ts
|
|
39
|
+
export const maxDuration = 30
|
|
40
|
+
export const DELETE = auth.approvable<Ctx>(need, describe, handler, { wait: 25 })
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
See [wait for an approval](../README.md#wait-for-an-approval).
|
|
44
|
+
|
|
45
|
+
## The client's address
|
|
46
|
+
|
|
47
|
+
The server uses the client's address for rate limits and the audit log. Anyone who connects to the app directly can send `X-Forwarded-For` and `X-Real-IP`, so the adapter reads a forwarded header only when you name it in `trustProxy`:
|
|
48
|
+
|
|
49
|
+
| `trustProxy` | The header the adapter reads |
|
|
50
|
+
|---|---|
|
|
51
|
+
| Unset or `false` | None |
|
|
52
|
+
| `{ header: 'x-forwarded-for', hops: n }` | The `n`th `X-Forwarded-For` entry from the right, for `n` proxies in a chain |
|
|
53
|
+
| `{ header: 'x-real-ip' }` | `X-Real-IP`, for a proxy that sets it |
|
|
54
|
+
| `true` | Shorthand for `x-forwarded-for` with 1 hop |
|
|
55
|
+
| A number `n` | Shorthand for `x-forwarded-for` with `n` hops |
|
|
56
|
+
|
|
57
|
+
The adapter reads only the header named. It never falls back from one header to the other, so a client-sent `X-Forwarded-For` can't override the `X-Real-IP` your proxy sets.
|
|
58
|
+
|
|
59
|
+
Next.js doesn't expose the socket's address, so without `trustProxy` the checks send no address, and with it the adapter reads the header on every request. The adapter can't tell your platform's proxy from a client. Set `trustProxy` only when the platform overwrites the header on every request, so a client can't reach the app with its own value. Vercel overwrites `X-Forwarded-For` and `X-Real-IP`, so on Vercel use `trustProxy: true`. Behind your own load balancer, make sure it replaces `X-Forwarded-For` rather than appending to it, or count its hops, and make sure clients can't reach the app around it.
|
|
60
|
+
|
|
61
|
+
`trustedProxies` lists your proxies' own addresses as CIDRs. Next.js has no socket address to check against it, so it only shortens the walk along `X-Forwarded-For`.
|
|
62
|
+
|
|
63
|
+
When you set `trustedProxies`, the walk along `X-Forwarded-For` also stops at the first entry outside them, and an entry that isn't an IP address stops it too, as in `authhttp`. A configuration that isn't valid, such as `hops: 0` or a malformed CIDR, throws when you create the adapter.
|
|
64
|
+
|
|
65
|
+
To read the address another way, pass `clientIp`, which overrides both options.
|
|
66
|
+
|
|
67
|
+
## Add `gate` on every page
|
|
68
|
+
|
|
69
|
+
Server Components and Server Actions see the request's headers, but not its method or URL. Cross-origin protection applies only to unsafe methods, and a Server Action is a POST. So the adapter checks a request it rebuilds from headers as a POST, unless `gate` in `proxy.ts`, which sees the real request, attests its method. The attestation carries a random token that lives only in the server process, and `gate` overwrites it on every request, so a client can't forge it. A Server Action is always checked as a POST.
|
|
70
|
+
|
|
71
|
+
Without `gate`, every page render is checked as unsafe: a same-site visit works, but a link to the page from another site is refused with `cross_origin`.
|
|
72
|
+
|
|
73
|
+
`gate` also:
|
|
74
|
+
|
|
75
|
+
- carries a session cookie that the server rotates. Server Components can't set cookies, so without `gate` a page-only app signs a person out when the old cookie's grace period ends. Route handlers wrapped in `auth.route` and the proxy routes carry rotated cookies on their own.
|
|
76
|
+
- sets the `x-tensile-path` request header, so a page's check names the page's URL in the audit log.
|
|
77
|
+
- redirects signed-out navigations to the pages in `matcher` to `signIn`.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
// proxy.ts
|
|
81
|
+
import { auth } from '@/lib/auth'
|
|
82
|
+
export const proxy = auth.gate({ matcher: ['/settings'] })
|
|
83
|
+
export const config = { matcher: ['/((?!_next/|auth/|api/|favicon.ico).*)'] }
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## See also
|
|
87
|
+
|
|
88
|
+
- [The example app](../examples/next/README.md)
|
|
89
|
+
- [The SDK](../README.md)
|