@tensile-tools/auth 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +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 +58 -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/gen/api.js
ADDED
package/dist/hono.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Context, Handler, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { type ApprovableOptions } from './adapt.ts';
|
|
3
|
+
import { type TrustProxy } from './clientip.ts';
|
|
4
|
+
import { type Action, type Need, type Principal, type Subject, type Tensile, type TensileOptions } from './core.ts';
|
|
5
|
+
import type { ProxyRoutes } from './proxy.ts';
|
|
6
|
+
export type { ApprovableOptions } from './adapt.ts';
|
|
7
|
+
/** The variables the adapter sets: `c.get('principal')`. */
|
|
8
|
+
export type TensileEnv = {
|
|
9
|
+
Variables: {
|
|
10
|
+
principal?: Principal;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
/** Options of the Hono adapter. */
|
|
14
|
+
export interface HonoOptions extends TensileOptions {
|
|
15
|
+
/**
|
|
16
|
+
* The forwarded header to read for the client's address. Under
|
|
17
|
+
* `@hono/node-server` or Bun, the adapter reads it only when the
|
|
18
|
+
* socket's address is in `trustedProxies`, and uses the socket's address
|
|
19
|
+
* otherwise. On runtimes that expose no socket address, it reads the
|
|
20
|
+
* header on every request, so the platform must overwrite it.
|
|
21
|
+
*/
|
|
22
|
+
trustProxy?: TrustProxy;
|
|
23
|
+
/** The proxies' own addresses, as CIDRs. Defaults to none. */
|
|
24
|
+
trustedProxies?: readonly string[];
|
|
25
|
+
/** Reads the client's address another way. Overrides `trustProxy`. */
|
|
26
|
+
clientIp?: (c: Context) => string | undefined;
|
|
27
|
+
}
|
|
28
|
+
/** The Hono adapter. */
|
|
29
|
+
export interface HonoAuth {
|
|
30
|
+
/** The core client. */
|
|
31
|
+
readonly client: Tensile;
|
|
32
|
+
/** Forwards the browser routes to the server: `app.all('/auth/*', auth.proxy())`. */
|
|
33
|
+
proxy(routes?: ProxyRoutes): Handler;
|
|
34
|
+
/** Sets `c.get('principal')`, or leaves it `undefined` when signed out. Refuses a bad bearer token with 401. */
|
|
35
|
+
authenticate(): MiddlewareHandler<TensileEnv>;
|
|
36
|
+
/** Lets the request through only when the principal meets `need`. */
|
|
37
|
+
need(need: Need): MiddlewareHandler<TensileEnv>;
|
|
38
|
+
/**
|
|
39
|
+
* Like `need`, and an agent that meets a human-only need may ask its
|
|
40
|
+
* human to approve the action `describe` returns. `options.wait`
|
|
41
|
+
* replaces `approvalWait` for this route. The check ends when the
|
|
42
|
+
* request's signal aborts.
|
|
43
|
+
*/
|
|
44
|
+
approvable(need: Need, describe: (c: Context) => Action | Promise<Action>, options?: ApprovableOptions): MiddlewareHandler<TensileEnv>;
|
|
45
|
+
/** Calls on the person's behalf, with the request's own credential. */
|
|
46
|
+
as(c: Context): Subject;
|
|
47
|
+
}
|
|
48
|
+
/** Creates the Hono adapter. */
|
|
49
|
+
export declare function tensile(options: HonoOptions): HonoAuth;
|
package/dist/hono.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The Hono 4 adapter.
|
|
2
|
+
import { decide } from "./adapt.js";
|
|
3
|
+
import { clientIpReader } from "./clientip.js";
|
|
4
|
+
import { createTensile, waitSeconds } from "./core.js";
|
|
5
|
+
function peerOf(c) {
|
|
6
|
+
const env = c.env;
|
|
7
|
+
if (env?.incoming?.socket)
|
|
8
|
+
return { address: env.incoming.socket.remoteAddress };
|
|
9
|
+
if (env?.requestIP)
|
|
10
|
+
return { address: env.requestIP(c.req.raw)?.address };
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
/** Creates the Hono adapter. */
|
|
14
|
+
export function tensile(options) {
|
|
15
|
+
const client = createTensile(options);
|
|
16
|
+
const read = clientIpReader(options);
|
|
17
|
+
const clientIp = options.clientIp ?? ((c) => read(c.req.raw.headers, peerOf(c)));
|
|
18
|
+
const gate = (g) => async (c, next) => {
|
|
19
|
+
const d = await decide(client, c.req.raw, { ...(await g(c)), clientIp: clientIp(c) });
|
|
20
|
+
if (d.kind === 'refused')
|
|
21
|
+
return d.response;
|
|
22
|
+
for (const [k, v] of Object.entries(d.headers))
|
|
23
|
+
c.header(k, v);
|
|
24
|
+
for (const ck of d.setCookies)
|
|
25
|
+
c.header('set-cookie', ck, { append: true });
|
|
26
|
+
c.set('principal', d.kind === 'allowed' ? d.principal : undefined);
|
|
27
|
+
await next();
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
client,
|
|
31
|
+
proxy(routes = {}) {
|
|
32
|
+
const handler = client.proxy(routes);
|
|
33
|
+
return c => handler(c.req.raw, { clientIp: clientIp(c) });
|
|
34
|
+
},
|
|
35
|
+
authenticate: () => gate(() => ({})),
|
|
36
|
+
need: need => gate(() => ({ need })),
|
|
37
|
+
approvable(need, describe, o = {}) {
|
|
38
|
+
const wait = o.wait === undefined ? undefined : waitSeconds(o.wait, 'wait');
|
|
39
|
+
return gate(async (c) => ({ need, action: await describe(c), wait }));
|
|
40
|
+
},
|
|
41
|
+
as: c => client.as(c.req.raw),
|
|
42
|
+
};
|
|
43
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { apiVersion, compareVersions, createTensile, credentialOf, encodeSubject, maxApprovalWait, onServerless, preferWait, readCookie, requestInfo, sdkVersion, seconds, serverURL, sessionCookie, signedOut, TensileError, waitSeconds, wireNeed, type Action, type Agent, type ApprovalCreated, type CheckInput, type CheckRequestInfo, type CheckResult, type Credential, type Meta, type Need, type Principal, type Session, type Subject, type Tensile, type TensileErrorKind, type TensileOptions, type User, type Delegated, type WireNeed, } from './core.ts';
|
|
2
|
+
export { problem, ProblemError, problemResponse, problemType, readProblem, stepUpCodes, unauthenticated, unavailable, wwwAuthenticate, type Assurance, type Challenge, type ChallengeApproval, type Method, type Problem, } from './problem.ts';
|
|
3
|
+
export { clientIpReader, ipOrUndefined, type ClientIpOptions, type Peer, type TrustProxy } from './clientip.ts';
|
|
4
|
+
export { BodyTooLargeError, maxBody, readBytes, readJSON, readText } from './body.ts';
|
|
5
|
+
export { createProxy, filterCookieHeader, isLibrarySetCookie, isProxied, libraryCookies, maxRequestBody, proxyPrefixes, type ProxyContext, type ProxyHandler, type ProxyOptions, type ProxyRoutes, } from './proxy.ts';
|
|
6
|
+
export { answerHook, signWebhook, verifyWebhook, WebhookError, type HookAnswer, type HookAnswerOptions, type WebhookEvent, type WebhookOptions } from './webhooks.ts';
|
|
7
|
+
export type { components, operations, paths } from './gen/api.ts';
|
|
8
|
+
export type { CheckRequest, SessionTree } from './api.ts';
|
|
9
|
+
export { maxCacheTtlMs, type CacheOptions, type CacheState } from './cache.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @tensile-tools/auth: the backend SDK of the tensile-auth server.
|
|
2
|
+
export { apiVersion, compareVersions, createTensile, credentialOf, encodeSubject, maxApprovalWait, onServerless, preferWait, readCookie, requestInfo, sdkVersion, seconds, serverURL, sessionCookie, signedOut, TensileError, waitSeconds, wireNeed, } from "./core.js";
|
|
3
|
+
export { problem, ProblemError, problemResponse, problemType, readProblem, stepUpCodes, unauthenticated, unavailable, wwwAuthenticate, } from "./problem.js";
|
|
4
|
+
export { clientIpReader, ipOrUndefined } from "./clientip.js";
|
|
5
|
+
export { BodyTooLargeError, maxBody, readBytes, readJSON, readText } from "./body.js";
|
|
6
|
+
export { createProxy, filterCookieHeader, isLibrarySetCookie, isProxied, libraryCookies, maxRequestBody, proxyPrefixes, } from "./proxy.js";
|
|
7
|
+
export { answerHook, signWebhook, verifyWebhook, WebhookError } from "./webhooks.js";
|
|
8
|
+
export { maxCacheTtlMs } from "./cache.js";
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { NextResponse, type NextRequest } from 'next/server';
|
|
2
|
+
import { type ApprovableOptions } from './adapt.ts';
|
|
3
|
+
import { type TrustProxy } from './clientip.ts';
|
|
4
|
+
import { type Action, type Credential, type Need, type Principal, type Subject, type Tensile, type TensileOptions } from './core.ts';
|
|
5
|
+
import type { ProxyRoutes } from './proxy.ts';
|
|
6
|
+
export type { ApprovableOptions } from './adapt.ts';
|
|
7
|
+
/** Options of the Next.js adapter. */
|
|
8
|
+
export interface NextOptions extends TensileOptions {
|
|
9
|
+
/** The sign-in page. Pages redirect there with `?next=` when signed out. */
|
|
10
|
+
signIn: string;
|
|
11
|
+
/** The step-up page. Defaults to `signIn`. Pages redirect there with `?next=` for a step-up challenge. */
|
|
12
|
+
stepUp?: string;
|
|
13
|
+
/** The app's public origin, for example `https://app.example.com`. Defaults to the request's `Host` and `X-Forwarded-Proto`. */
|
|
14
|
+
appUrl?: string;
|
|
15
|
+
/** The optional route groups the proxy forwards. */
|
|
16
|
+
routes?: ProxyRoutes;
|
|
17
|
+
/**
|
|
18
|
+
* The forwarded header to read for the client's address. Next.js
|
|
19
|
+
* doesn't expose the socket's address, so without it the checks send
|
|
20
|
+
* no address, and with it the adapter reads the header on every
|
|
21
|
+
* request. Set it only when the platform overwrites that header, as
|
|
22
|
+
* Vercel does with `X-Forwarded-For` and `X-Real-IP`.
|
|
23
|
+
*/
|
|
24
|
+
trustProxy?: TrustProxy;
|
|
25
|
+
/**
|
|
26
|
+
* The proxies' own addresses, as CIDRs. With more than 1 hop, the walk
|
|
27
|
+
* along `X-Forwarded-For` stops at the first entry outside these.
|
|
28
|
+
*/
|
|
29
|
+
trustedProxies?: readonly string[];
|
|
30
|
+
/** Reads the client's address another way. Overrides `trustProxy`. */
|
|
31
|
+
clientIp?: (h: Headers) => string | undefined;
|
|
32
|
+
}
|
|
33
|
+
/** A route handler. */
|
|
34
|
+
export type RouteHandler<C = unknown> = (req: Request, ctx: C) => Response | Promise<Response>;
|
|
35
|
+
/** The handlers to export from `app/auth/[...path]/route.ts`. */
|
|
36
|
+
export interface ProxyRouteHandlers {
|
|
37
|
+
GET: ProxyRoute;
|
|
38
|
+
POST: ProxyRoute;
|
|
39
|
+
PUT: ProxyRoute;
|
|
40
|
+
PATCH: ProxyRoute;
|
|
41
|
+
DELETE: ProxyRoute;
|
|
42
|
+
HEAD: ProxyRoute;
|
|
43
|
+
OPTIONS: ProxyRoute;
|
|
44
|
+
}
|
|
45
|
+
/** A proxy route handler. It ignores Next.js's `{params}`. */
|
|
46
|
+
export type ProxyRoute = (req: Request) => Promise<Response>;
|
|
47
|
+
/** Options of `gate`, for `proxy.ts`. */
|
|
48
|
+
export interface GateOptions {
|
|
49
|
+
/** Path prefixes or patterns that need a session. Defaults to every path except the proxied routes and the sign-in page. */
|
|
50
|
+
matcher?: (string | RegExp)[];
|
|
51
|
+
/** The sign-in page. Defaults to the adapter's `signIn`. */
|
|
52
|
+
signIn?: string;
|
|
53
|
+
/**
|
|
54
|
+
* Checks the cookie with the server on each gated navigation, so a
|
|
55
|
+
* rotated cookie reaches the browser even though Server Components
|
|
56
|
+
* can't set cookies. Defaults to true.
|
|
57
|
+
*/
|
|
58
|
+
check?: boolean;
|
|
59
|
+
}
|
|
60
|
+
/** The Next.js adapter. */
|
|
61
|
+
export interface NextAuth {
|
|
62
|
+
/** The core client. */
|
|
63
|
+
readonly client: Tensile;
|
|
64
|
+
/** The proxy: `export const { GET, POST } = auth.proxy` in `app/auth/[...path]/route.ts`. */
|
|
65
|
+
readonly proxy: ProxyRouteHandlers;
|
|
66
|
+
/** The signed-in principal, or `undefined`. Works in Server Components, Server Actions, and route handlers. */
|
|
67
|
+
principal(): Promise<Principal | undefined>;
|
|
68
|
+
/**
|
|
69
|
+
* The principal, when it meets `need`. Otherwise a page or Server Action
|
|
70
|
+
* redirects to the sign-in or step-up page, and a handler wrapped in
|
|
71
|
+
* `route` answers the problem.
|
|
72
|
+
*/
|
|
73
|
+
require(need?: Need): Promise<Principal>;
|
|
74
|
+
/** Wraps a route handler so that `require` inside it answers problems, and the server's cookies reach its response. */
|
|
75
|
+
route<C>(handler: RouteHandler<C>): RouteHandler<C>;
|
|
76
|
+
/**
|
|
77
|
+
* A route handler that an agent may ask its human to approve, like
|
|
78
|
+
* `authhttp.Approvable`. `options.wait` replaces `approvalWait` for this
|
|
79
|
+
* route; on Vercel, export `maxDuration` of at least that plus 5. The
|
|
80
|
+
* check ends when `req.signal` aborts.
|
|
81
|
+
*/
|
|
82
|
+
approvable<C>(need: Need, describe: (req: Request, ctx: C) => Action | Promise<Action>, handler: (req: Request, ctx: C & {
|
|
83
|
+
principal: Principal;
|
|
84
|
+
}) => Response | Promise<Response>, options?: ApprovableOptions): RouteHandler<C>;
|
|
85
|
+
/** The current request's credential, for `as`. Throws a 401 `ProblemError` when there is none. */
|
|
86
|
+
subject(): Promise<Credential>;
|
|
87
|
+
/** Calls on a person's behalf. */
|
|
88
|
+
as(subject: Credential | Request): Subject;
|
|
89
|
+
/** A `proxy.ts` (formerly `middleware.ts`) function that redirects signed-out navigations early. It never replaces `require`. */
|
|
90
|
+
gate(options?: GateOptions): (req: NextRequest) => Promise<NextResponse>;
|
|
91
|
+
}
|
|
92
|
+
export { methodHeader, pathHeader } from './rebuild.ts';
|
|
93
|
+
/** Creates the Next.js adapter. */
|
|
94
|
+
export declare function tensile(options: NextOptions): NextAuth;
|
|
95
|
+
type CookieSpec = {
|
|
96
|
+
name: string;
|
|
97
|
+
value: string;
|
|
98
|
+
path?: string;
|
|
99
|
+
expires?: Date;
|
|
100
|
+
maxAge?: number;
|
|
101
|
+
secure?: boolean;
|
|
102
|
+
httpOnly?: boolean;
|
|
103
|
+
sameSite?: 'lax' | 'strict' | 'none';
|
|
104
|
+
};
|
|
105
|
+
/** Parses a `Set-Cookie` value into the options `cookies().set` takes. */
|
|
106
|
+
export declare function parseSetCookie(header: string): CookieSpec;
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// The Next.js adapter, for the App Router on the Node.js runtime.
|
|
2
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
3
|
+
import { cookies, headers } from 'next/headers';
|
|
4
|
+
import { redirect } from 'next/navigation';
|
|
5
|
+
import { NextResponse } from 'next/server';
|
|
6
|
+
import { decide } from "./adapt.js";
|
|
7
|
+
import { clientIpReader } from "./clientip.js";
|
|
8
|
+
import { createTensile, credentialOf, sessionCookie, waitSeconds, } from "./core.js";
|
|
9
|
+
import { ProblemError, stepUpCodes, unauthenticated } from "./problem.js";
|
|
10
|
+
import { attestMethod, methodHeader, pathHeader, rebuildRequest } from "./rebuild.js";
|
|
11
|
+
export { methodHeader, pathHeader } from "./rebuild.js";
|
|
12
|
+
/** Creates the Next.js adapter. */
|
|
13
|
+
export function tensile(options) {
|
|
14
|
+
const client = createTensile(options);
|
|
15
|
+
const handler = client.proxy(options.routes);
|
|
16
|
+
const scope = new AsyncLocalStorage();
|
|
17
|
+
const read = clientIpReader(options);
|
|
18
|
+
const clientIp = options.clientIp ?? ((h) => read(h, undefined));
|
|
19
|
+
const stepUp = options.stepUp ?? options.signIn;
|
|
20
|
+
const proxied = req => handler(req, { clientIp: clientIp(req.headers) });
|
|
21
|
+
// current describes the request being served: the route's own request,
|
|
22
|
+
// or one rebuilt from headers() in a Server Component or Server Action.
|
|
23
|
+
async function current() {
|
|
24
|
+
const s = scope.getStore();
|
|
25
|
+
if (s)
|
|
26
|
+
return { req: s.req, inRoute: s };
|
|
27
|
+
const h = new Headers(await headers());
|
|
28
|
+
return { req: rebuildRequest(h, options.appUrl), inRoute: undefined };
|
|
29
|
+
}
|
|
30
|
+
// carry applies a decision's cookies and headers: to the route's response
|
|
31
|
+
// inside `route`, or through cookies() elsewhere. Server Components can't
|
|
32
|
+
// set cookies; `gate` covers them.
|
|
33
|
+
async function carry(d, inRoute) {
|
|
34
|
+
if (d.kind === 'refused')
|
|
35
|
+
return;
|
|
36
|
+
if (inRoute) {
|
|
37
|
+
inRoute.cookies.push(...d.setCookies);
|
|
38
|
+
Object.assign(inRoute.headers, d.headers);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (!d.setCookies.length)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
const jar = await cookies();
|
|
45
|
+
for (const c of d.setCookies)
|
|
46
|
+
jar.set(parseSetCookie(c));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// A Server Component render: cookies are read-only here.
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function check(gate) {
|
|
53
|
+
const { req, inRoute } = await current();
|
|
54
|
+
const d = await decide(client, req, { ...gate, clientIp: clientIp(req.headers) });
|
|
55
|
+
await carry(d, inRoute);
|
|
56
|
+
return { d, req, inRoute };
|
|
57
|
+
}
|
|
58
|
+
function withNext(page, req) {
|
|
59
|
+
const u = new URL(req.url);
|
|
60
|
+
return `${page}${page.includes('?') ? '&' : '?'}next=${encodeURIComponent(u.pathname + u.search)}`;
|
|
61
|
+
}
|
|
62
|
+
async function finish(res, s) {
|
|
63
|
+
if (!s.cookies.length && !Object.keys(s.headers).length)
|
|
64
|
+
return res;
|
|
65
|
+
const h = new Headers(res.headers);
|
|
66
|
+
for (const [k, v] of Object.entries(s.headers))
|
|
67
|
+
if (!h.has(k))
|
|
68
|
+
h.set(k, v);
|
|
69
|
+
for (const c of s.cookies)
|
|
70
|
+
h.append('set-cookie', c);
|
|
71
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h });
|
|
72
|
+
}
|
|
73
|
+
function route(fn) {
|
|
74
|
+
return async (req, ctx) => {
|
|
75
|
+
const s = { req, cookies: [], headers: {} };
|
|
76
|
+
return scope.run(s, async () => {
|
|
77
|
+
try {
|
|
78
|
+
return await finish(await fn(req, ctx), s);
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (err instanceof ProblemError)
|
|
82
|
+
return finish(err.toResponse(), s);
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
async function require(need) {
|
|
89
|
+
const { d, req, inRoute } = await check(need ? { need } : {});
|
|
90
|
+
if (d.kind === 'allowed')
|
|
91
|
+
return d.principal;
|
|
92
|
+
const p = d.kind === 'refused' ? d.problem : unauthenticated;
|
|
93
|
+
if (inRoute)
|
|
94
|
+
throw new ProblemError(p, d.kind === 'refused' ? d.response.headers : undefined);
|
|
95
|
+
if (p.status === 401)
|
|
96
|
+
redirect(withNext(options.signIn, req));
|
|
97
|
+
if (stepUpCodes.has(p.code))
|
|
98
|
+
redirect(withNext(stepUp, req));
|
|
99
|
+
throw new ProblemError(p);
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
client,
|
|
103
|
+
proxy: { GET: proxied, POST: proxied, PUT: proxied, PATCH: proxied, DELETE: proxied, HEAD: proxied, OPTIONS: proxied },
|
|
104
|
+
async principal() {
|
|
105
|
+
const { d } = await check({});
|
|
106
|
+
if (d.kind === 'refused')
|
|
107
|
+
throw new ProblemError(d.problem);
|
|
108
|
+
return d.kind === 'allowed' ? d.principal : undefined;
|
|
109
|
+
},
|
|
110
|
+
require,
|
|
111
|
+
route,
|
|
112
|
+
approvable(need, describe, fn, o = {}) {
|
|
113
|
+
const wait = o.wait === undefined ? undefined : waitSeconds(o.wait, 'wait');
|
|
114
|
+
return route(async (req, ctx) => {
|
|
115
|
+
const s = scope.getStore();
|
|
116
|
+
const d = await decide(client, req, { need, action: await describe(req, ctx), clientIp: clientIp(req.headers), wait });
|
|
117
|
+
if (d.kind === 'refused')
|
|
118
|
+
return d.response;
|
|
119
|
+
await carry(d, s);
|
|
120
|
+
return fn(req, { ...ctx, principal: d.principal });
|
|
121
|
+
});
|
|
122
|
+
},
|
|
123
|
+
async subject() {
|
|
124
|
+
const { req } = await current();
|
|
125
|
+
const c = credentialOf(req);
|
|
126
|
+
if (!c)
|
|
127
|
+
throw new ProblemError(unauthenticated);
|
|
128
|
+
return c;
|
|
129
|
+
},
|
|
130
|
+
as: subject => client.as(subject),
|
|
131
|
+
gate(g = {}) {
|
|
132
|
+
const signIn = g.signIn ?? options.signIn;
|
|
133
|
+
const skip = ['/auth/', '/_next/', signIn];
|
|
134
|
+
const gated = (path) => g.matcher
|
|
135
|
+
? g.matcher.some(m => typeof m === 'string' ? path === m || path.startsWith(m.endsWith('/') ? m : m + '/') : m.test(path))
|
|
136
|
+
: !skip.some(p => path === p || path.startsWith(p));
|
|
137
|
+
return async (req) => {
|
|
138
|
+
const url = req.nextUrl;
|
|
139
|
+
const reqHeaders = new Headers(req.headers);
|
|
140
|
+
// Set on every request, so a client's own values never pass through.
|
|
141
|
+
reqHeaders.set(pathHeader, url.pathname + url.search);
|
|
142
|
+
reqHeaders.set(methodHeader, attestMethod(req.method));
|
|
143
|
+
if (!gated(url.pathname))
|
|
144
|
+
return NextResponse.next({ request: { headers: reqHeaders } });
|
|
145
|
+
const toSignIn = () => NextResponse.redirect(new URL(withNext(signIn, req), url));
|
|
146
|
+
if (!credentialOf(req))
|
|
147
|
+
return toSignIn();
|
|
148
|
+
if (g.check === false)
|
|
149
|
+
return NextResponse.next({ request: { headers: reqHeaders } });
|
|
150
|
+
const d = await decide(client, req, { clientIp: clientIp(req.headers) });
|
|
151
|
+
if (d.kind === 'refused')
|
|
152
|
+
return new NextResponse(d.response.body, { status: d.response.status, headers: d.response.headers });
|
|
153
|
+
if (d.kind === 'anonymous') {
|
|
154
|
+
const res = toSignIn();
|
|
155
|
+
for (const c of d.setCookies)
|
|
156
|
+
res.headers.append('set-cookie', c);
|
|
157
|
+
return res;
|
|
158
|
+
}
|
|
159
|
+
// A rotated cookie goes to the browser and to this request's render.
|
|
160
|
+
const rotated = d.setCookies.map(parseSetCookie).find(c => c.name === sessionCookie);
|
|
161
|
+
if (rotated) {
|
|
162
|
+
const jar = (reqHeaders.get('cookie') ?? '').split(';').map(s => s.trim()).filter(s => s && !s.startsWith(sessionCookie + '='));
|
|
163
|
+
reqHeaders.set('cookie', [...jar, `${sessionCookie}=${rotated.value}`].join('; '));
|
|
164
|
+
}
|
|
165
|
+
const res = NextResponse.next({ request: { headers: reqHeaders } });
|
|
166
|
+
for (const [k, v] of Object.entries(d.headers))
|
|
167
|
+
res.headers.set(k, v);
|
|
168
|
+
for (const c of d.setCookies)
|
|
169
|
+
res.headers.append('set-cookie', c);
|
|
170
|
+
return res;
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/** Parses a `Set-Cookie` value into the options `cookies().set` takes. */
|
|
176
|
+
export function parseSetCookie(header) {
|
|
177
|
+
const [pair, ...attrs] = header.split(';');
|
|
178
|
+
const i = pair.indexOf('=');
|
|
179
|
+
const c = { name: pair.slice(0, i).trim(), value: pair.slice(i + 1).trim() };
|
|
180
|
+
for (const a of attrs) {
|
|
181
|
+
const [k, ...rest] = a.split('=');
|
|
182
|
+
const v = rest.join('=').trim();
|
|
183
|
+
switch (k.trim().toLowerCase()) {
|
|
184
|
+
case 'path':
|
|
185
|
+
c.path = v;
|
|
186
|
+
break;
|
|
187
|
+
case 'expires':
|
|
188
|
+
c.expires = new Date(v);
|
|
189
|
+
break;
|
|
190
|
+
case 'max-age':
|
|
191
|
+
c.maxAge = Number(v);
|
|
192
|
+
break;
|
|
193
|
+
case 'secure':
|
|
194
|
+
c.secure = true;
|
|
195
|
+
break;
|
|
196
|
+
case 'httponly':
|
|
197
|
+
c.httpOnly = true;
|
|
198
|
+
break;
|
|
199
|
+
case 'samesite':
|
|
200
|
+
c.sameSite = v.toLowerCase();
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return c;
|
|
205
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Problem } from '@tensile-tools/auth-client';
|
|
2
|
+
export type { Assurance, Challenge, ChallengeApproval, Method, Problem } from '@tensile-tools/auth-client';
|
|
3
|
+
/** The media type of problem responses. */
|
|
4
|
+
export declare const problemType = "application/problem+json";
|
|
5
|
+
/** Codes whose challenge a step-up can satisfy. */
|
|
6
|
+
export declare const stepUpCodes: ReadonlySet<string>;
|
|
7
|
+
/** Builds a problem with the `urn:tensile:auth:problem:` type for `code`. */
|
|
8
|
+
export declare function problem(status: number, code: string, title: string, fix?: string): Problem;
|
|
9
|
+
/** The problem every missing or rejected credential gets. */
|
|
10
|
+
export declare const unauthenticated: Problem;
|
|
11
|
+
/** The problem an adapter answers when the server can't decide. Never a 401. */
|
|
12
|
+
export declare const unavailable: Problem;
|
|
13
|
+
/**
|
|
14
|
+
* Turns a problem into a response. A step-up challenge gets the RFC 9470
|
|
15
|
+
* `WWW-Authenticate` header, and a throttle gets `Retry-After`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function problemResponse(p: Problem, init?: {
|
|
18
|
+
headers?: HeadersInit;
|
|
19
|
+
}): Response;
|
|
20
|
+
/**
|
|
21
|
+
* The `WWW-Authenticate` header for a problem, as `authhttp.WriteProblem`
|
|
22
|
+
* writes it: an RFC 9470 `insufficient_user_authentication` challenge for
|
|
23
|
+
* a step-up, plain `Bearer` for a 401, and nothing otherwise.
|
|
24
|
+
*/
|
|
25
|
+
export declare function wwwAuthenticate(p: Problem): string | undefined;
|
|
26
|
+
/** An error that carries a problem: a refusal of a call made for a person, or a refusal thrown by `require`. */
|
|
27
|
+
export declare class ProblemError extends Error {
|
|
28
|
+
readonly problem: Problem;
|
|
29
|
+
/** Headers and cookies to send with the problem, for example a cleared cookie. */
|
|
30
|
+
readonly headers: Headers;
|
|
31
|
+
constructor(problem: Problem, headers?: HeadersInit);
|
|
32
|
+
/** The problem as a response, with its headers. */
|
|
33
|
+
toResponse(): Response;
|
|
34
|
+
}
|
|
35
|
+
/** Reads a problem from a failed response, or makes one with the code `http_<status>`. */
|
|
36
|
+
export declare function readProblem(res: Response): Promise<Problem>;
|
package/dist/problem.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Problem details (RFC 9457): the browser client's types, re-exported,
|
|
2
|
+
// and the helpers a backend needs to answer with them.
|
|
3
|
+
import { readJSON } from "./body.js";
|
|
4
|
+
/** The media type of problem responses. */
|
|
5
|
+
export const problemType = 'application/problem+json';
|
|
6
|
+
/** Codes whose challenge a step-up can satisfy. */
|
|
7
|
+
export const stepUpCodes = new Set(['step_up_required', 'stronger_factor_required']);
|
|
8
|
+
/** Builds a problem with the `urn:tensile:auth:problem:` type for `code`. */
|
|
9
|
+
export function problem(status, code, title, fix) {
|
|
10
|
+
return { type: `urn:tensile:auth:problem:${code}`, title, status, code, ...(fix ? { fix } : {}) };
|
|
11
|
+
}
|
|
12
|
+
/** The problem every missing or rejected credential gets. */
|
|
13
|
+
export const unauthenticated = problem(401, 'unauthenticated', 'Sign in to continue', 'Sign in again.');
|
|
14
|
+
/** The problem an adapter answers when the server can't decide. Never a 401. */
|
|
15
|
+
export const unavailable = problem(503, 'unavailable', 'Try again shortly', 'Try again in a few seconds.');
|
|
16
|
+
/**
|
|
17
|
+
* Turns a problem into a response. A step-up challenge gets the RFC 9470
|
|
18
|
+
* `WWW-Authenticate` header, and a throttle gets `Retry-After`.
|
|
19
|
+
*/
|
|
20
|
+
export function problemResponse(p, init = {}) {
|
|
21
|
+
const headers = new Headers(init.headers);
|
|
22
|
+
headers.set('content-type', problemType);
|
|
23
|
+
headers.set('cache-control', 'no-store');
|
|
24
|
+
headers.set('x-content-type-options', 'nosniff');
|
|
25
|
+
const www = wwwAuthenticate(p);
|
|
26
|
+
if (www && !headers.has('www-authenticate'))
|
|
27
|
+
headers.set('www-authenticate', www);
|
|
28
|
+
if (p.retry_after && !headers.has('retry-after'))
|
|
29
|
+
headers.set('retry-after', String(p.retry_after));
|
|
30
|
+
return new Response(JSON.stringify(p), { status: p.status, headers });
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The `WWW-Authenticate` header for a problem, as `authhttp.WriteProblem`
|
|
34
|
+
* writes it: an RFC 9470 `insufficient_user_authentication` challenge for
|
|
35
|
+
* a step-up, plain `Bearer` for a 401, and nothing otherwise.
|
|
36
|
+
*/
|
|
37
|
+
export function wwwAuthenticate(p) {
|
|
38
|
+
if (stepUpCodes.has(p.code)) {
|
|
39
|
+
let v = `Bearer error="insufficient_user_authentication", error_description="${p.title.replace(/["\\]/g, '')}"`;
|
|
40
|
+
if (p.challenge?.within_seconds)
|
|
41
|
+
v += `, max_age=${p.challenge.within_seconds}`;
|
|
42
|
+
return v;
|
|
43
|
+
}
|
|
44
|
+
if (p.status === 401)
|
|
45
|
+
return 'Bearer';
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
/** An error that carries a problem: a refusal of a call made for a person, or a refusal thrown by `require`. */
|
|
49
|
+
export class ProblemError extends Error {
|
|
50
|
+
problem;
|
|
51
|
+
/** Headers and cookies to send with the problem, for example a cleared cookie. */
|
|
52
|
+
headers;
|
|
53
|
+
constructor(problem, headers) {
|
|
54
|
+
super(problem.fix ? `${problem.title}. ${problem.fix}` : problem.title);
|
|
55
|
+
this.name = 'ProblemError';
|
|
56
|
+
this.problem = problem;
|
|
57
|
+
this.headers = new Headers(headers);
|
|
58
|
+
}
|
|
59
|
+
/** The problem as a response, with its headers. */
|
|
60
|
+
toResponse() {
|
|
61
|
+
return problemResponse(this.problem, { headers: this.headers });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Reads a problem from a failed response, or makes one with the code `http_<status>`. */
|
|
65
|
+
export async function readProblem(res) {
|
|
66
|
+
const type = res.headers.get('content-type') ?? '';
|
|
67
|
+
if (type.startsWith(problemType) || type.startsWith('application/json')) {
|
|
68
|
+
try {
|
|
69
|
+
const body = await readJSON(res);
|
|
70
|
+
if (typeof body.code === 'string' && typeof body.title === 'string') {
|
|
71
|
+
return { ...body, status: body.status ?? res.status };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// Fall through to the generic problem.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return problem(res.status, `http_${res.status}`, res.statusText || 'Request failed', 'Try again.');
|
|
79
|
+
}
|
package/dist/proxy.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Which optional route groups the proxy forwards. `/auth/` is always on. */
|
|
2
|
+
export interface ProxyRoutes {
|
|
3
|
+
/** `/admin/`: the admin API. */
|
|
4
|
+
admin?: boolean;
|
|
5
|
+
/** `/login/oauth/`: the OAuth provider. */
|
|
6
|
+
oauth?: boolean;
|
|
7
|
+
/** `/login/device/`: the device authorization grant. */
|
|
8
|
+
device?: boolean;
|
|
9
|
+
/** `/.well-known/`: OpenID and OAuth metadata. */
|
|
10
|
+
wellKnown?: boolean;
|
|
11
|
+
}
|
|
12
|
+
/** Options of `createProxy`. */
|
|
13
|
+
export interface ProxyOptions extends ProxyRoutes {
|
|
14
|
+
url: string;
|
|
15
|
+
appKey: string;
|
|
16
|
+
/** How long the server may take to answer, in milliseconds. Defaults to 30,000. */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
/**
|
|
19
|
+
* How long the server may take to answer `/auth/claims/`, in
|
|
20
|
+
* milliseconds. A claim long-polls for up to 60 seconds, so it defaults
|
|
21
|
+
* to 65,000.
|
|
22
|
+
*/
|
|
23
|
+
claimTimeoutMs?: number;
|
|
24
|
+
/** Replaces `fetch`, for tests. */
|
|
25
|
+
fetch?: typeof globalThis.fetch;
|
|
26
|
+
}
|
|
27
|
+
/** Per-request facts that only the framework knows. */
|
|
28
|
+
export interface ProxyContext {
|
|
29
|
+
/** The client's address, as the framework reports it. Sent as `Tensile-Client-IP`. */
|
|
30
|
+
clientIp?: string;
|
|
31
|
+
}
|
|
32
|
+
/** A Fetch API handler. */
|
|
33
|
+
export type ProxyHandler = (request: Request, context?: ProxyContext) => Promise<Response>;
|
|
34
|
+
/** The library's cookies: the only ones the proxy forwards, in either direction. */
|
|
35
|
+
export declare const libraryCookies: ReadonlySet<string>;
|
|
36
|
+
/** The largest request body the proxy forwards: 1 MiB. */
|
|
37
|
+
export declare const maxRequestBody: number;
|
|
38
|
+
/** The path prefixes the proxy forwards for `routes`. */
|
|
39
|
+
export declare function proxyPrefixes(routes?: ProxyRoutes): string[];
|
|
40
|
+
/**
|
|
41
|
+
* Reports whether the proxy forwards `pathname`, which must be the raw,
|
|
42
|
+
* still-encoded path. Encoded dots, slashes, and backslashes, and empty
|
|
43
|
+
* segments, are refused, so no path reaches a route outside the prefixes
|
|
44
|
+
* after the server decodes it.
|
|
45
|
+
*/
|
|
46
|
+
export declare function isProxied(pathname: string, routes?: ProxyRoutes): boolean;
|
|
47
|
+
/** Keeps only the library's cookies in a `Cookie` header. */
|
|
48
|
+
export declare function filterCookieHeader(header: string | null): string | undefined;
|
|
49
|
+
/** Reports whether a `Set-Cookie` value sets one of the library's cookies. */
|
|
50
|
+
export declare function isLibrarySetCookie(value: string): boolean;
|
|
51
|
+
/**
|
|
52
|
+
* Creates the proxy. It forwards allowlisted paths with the library's
|
|
53
|
+
* cookies and a fixed set of headers, adds the app key and the client's
|
|
54
|
+
* address, and returns the server's status, body, and allowlisted
|
|
55
|
+
* headers. Any other path answers 404 without reaching the server.
|
|
56
|
+
*/
|
|
57
|
+
export declare function createProxy(o: ProxyOptions): ProxyHandler;
|