@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/core.d.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import type { Action, Agent, ApprovalCreated, CheckRequestInfo, CheckResult, Credential, Delegated, Meta, Principal, Session, User, WireNeed } from './api.ts';
|
|
2
|
+
import { problem, ProblemError, type Assurance, type Problem } from './problem.ts';
|
|
3
|
+
import { type CacheOptions, type CacheState } from './cache.ts';
|
|
4
|
+
import { type ProxyHandler, type ProxyRoutes } from './proxy.ts';
|
|
5
|
+
import { serverURL } from './transport.ts';
|
|
6
|
+
import { type HookAnswer, type WebhookEvent, type WebhookOptions } from './webhooks.ts';
|
|
7
|
+
export type { Action, Agent, ApprovalCreated, CheckRequestInfo, CheckResult, Credential, Delegated, Meta, Principal, Session, User, WireNeed };
|
|
8
|
+
/** The SDK's version, sent as `Tensile-Auth-SDK`. It is the version of the Go module, the image, and the browser client. */
|
|
9
|
+
export declare const sdkVersion = "0.4.1";
|
|
10
|
+
/** The API version the SDK was written against. */
|
|
11
|
+
export declare const apiVersion = "v1";
|
|
12
|
+
/** The name of the session cookie. */
|
|
13
|
+
export declare const sessionCookie = "__Host-session";
|
|
14
|
+
/**
|
|
15
|
+
* What an operation requires of its caller. `within` is seconds, or a
|
|
16
|
+
* duration such as `'10m'` or `'1h30m'`.
|
|
17
|
+
*/
|
|
18
|
+
export interface Need {
|
|
19
|
+
action: string;
|
|
20
|
+
human?: boolean;
|
|
21
|
+
assurance?: Assurance;
|
|
22
|
+
within?: number | string;
|
|
23
|
+
scopes?: string[];
|
|
24
|
+
/**
|
|
25
|
+
* How long an approval for this need lives, from 1 minute to 24 hours:
|
|
26
|
+
* seconds, or a duration such as `'2h'`. Defaults to 5 minutes. Set it
|
|
27
|
+
* for agents that run in the background.
|
|
28
|
+
*/
|
|
29
|
+
approvalTtl?: number | string;
|
|
30
|
+
}
|
|
31
|
+
/** The input of `check`. */
|
|
32
|
+
export interface CheckInput {
|
|
33
|
+
credential: Credential;
|
|
34
|
+
request: CheckRequestInfo;
|
|
35
|
+
need?: Need;
|
|
36
|
+
/**
|
|
37
|
+
* An approval to redeem (`id` set), or the action to create one for.
|
|
38
|
+
* `wait` is seconds, 0 to 60, sent as `Prefer: wait=N`: on a redeem,
|
|
39
|
+
* how long the server holds the check for the person's decision, and
|
|
40
|
+
* on a create, the longest wait the refusal offers the agent. Without
|
|
41
|
+
* it the server doesn't wait, and the refusal tells the agent to retry
|
|
42
|
+
* after `Retry-After`. A waiting check's timeout is `wait` seconds
|
|
43
|
+
* plus `timeoutMs`.
|
|
44
|
+
*/
|
|
45
|
+
approval?: {
|
|
46
|
+
id?: string;
|
|
47
|
+
action: Action;
|
|
48
|
+
wait?: number;
|
|
49
|
+
};
|
|
50
|
+
/** The canonical URI of the resource this app serves, for tokens bound to a resource. */
|
|
51
|
+
resource?: string;
|
|
52
|
+
/** Aborts the check, for example when the end user disconnects. `check` then rejects with the signal's reason. */
|
|
53
|
+
signal?: AbortSignal;
|
|
54
|
+
}
|
|
55
|
+
/** Options of `createTensile`. */
|
|
56
|
+
export interface TensileOptions {
|
|
57
|
+
/** The server's URL, for example `http://tensile-auth:8080`. `http://` works only for loopback, private, and single-label hosts. */
|
|
58
|
+
url: string;
|
|
59
|
+
/** The app key, `tsx_…`. Create one with `tensile-auth-server app-key create NAME`. */
|
|
60
|
+
appKey: string;
|
|
61
|
+
/** How long each call may take, in milliseconds. Defaults to 5,000. */
|
|
62
|
+
timeoutMs?: number;
|
|
63
|
+
/** Runs the first time this process sees a user ID, before the request continues. */
|
|
64
|
+
onFirstSeen?: (principal: Principal) => void | Promise<void>;
|
|
65
|
+
/** The secret, or secrets while one rotates, that sign webhooks and hooks: `whsec_…`. */
|
|
66
|
+
webhookSecret?: string | string[];
|
|
67
|
+
/** Replaces `fetch`, for tests. */
|
|
68
|
+
fetch?: typeof globalThis.fetch;
|
|
69
|
+
/** Receives warnings, such as a server older than the SDK. Defaults to `console.warn`. */
|
|
70
|
+
warn?: (message: string) => void;
|
|
71
|
+
/**
|
|
72
|
+
* The longest an approvable route holds an agent's retry for its
|
|
73
|
+
* person's decision: seconds from 0 to 60, or a duration such as
|
|
74
|
+
* `'25s'`. The agent asks with `Prefer: wait=N`; the wait is the
|
|
75
|
+
* smallest of N, this, and the approval's remaining life, and the
|
|
76
|
+
* refusal offers no more than this. 0 turns waiting off, and the agent
|
|
77
|
+
* retries after `Retry-After` instead.
|
|
78
|
+
*
|
|
79
|
+
* Defaults to 50 on a long-running server, under the common 60-second
|
|
80
|
+
* proxy idle timeout, and to 0 on a detected serverless platform
|
|
81
|
+
* (`VERCEL`, `AWS_LAMBDA_FUNCTION_NAME`, `NETLIFY`, or an edge
|
|
82
|
+
* runtime), where a function stopped mid-wait can spend the approval
|
|
83
|
+
* without running the route. On serverless, set it with the function's
|
|
84
|
+
* limit: `maxDuration >= approvalWait + 5`.
|
|
85
|
+
*/
|
|
86
|
+
approvalWait?: number | string;
|
|
87
|
+
/**
|
|
88
|
+
* Caches allowed `check` answers for up to 30 seconds while the server's
|
|
89
|
+
* event stream is connected, and clears them on every change it reports.
|
|
90
|
+
* Off by default. Turn it on only in a long-running process: it holds a
|
|
91
|
+
* connection to the server. Call `close()` to stop it.
|
|
92
|
+
*/
|
|
93
|
+
cache?: boolean | CacheOptions;
|
|
94
|
+
}
|
|
95
|
+
/** Why a call failed without a decision. Adapters answer every one of them with 503, never 401. */
|
|
96
|
+
export type TensileErrorKind = 'outage' | 'app_key' | 'throttled' | 'bad_request' | 'no_v1';
|
|
97
|
+
/** A call that the server couldn't decide: an outage, a bad or throttled app key, or a malformed call. */
|
|
98
|
+
export declare class TensileError extends Error {
|
|
99
|
+
readonly kind: TensileErrorKind;
|
|
100
|
+
readonly status?: number;
|
|
101
|
+
readonly problem?: Problem;
|
|
102
|
+
readonly retryAfter?: number;
|
|
103
|
+
constructor(kind: TensileErrorKind, message: string, o?: {
|
|
104
|
+
status?: number;
|
|
105
|
+
problem?: Problem;
|
|
106
|
+
retryAfter?: number;
|
|
107
|
+
cause?: unknown;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** Calls that act for a person, from `as(subject)`. */
|
|
111
|
+
export interface Subject {
|
|
112
|
+
agents: {
|
|
113
|
+
/** Creates an agent owned by the subject. */
|
|
114
|
+
create(spec: {
|
|
115
|
+
name: string;
|
|
116
|
+
scopes: string[];
|
|
117
|
+
}): Promise<Agent>;
|
|
118
|
+
/** Delegates a token for agent `id` from the subject's session. The token is shown once. */
|
|
119
|
+
delegate(id: string, spec: {
|
|
120
|
+
scopes: string[];
|
|
121
|
+
name?: string;
|
|
122
|
+
ttl?: number | string;
|
|
123
|
+
keyThumbprint?: string;
|
|
124
|
+
}): Promise<Delegated>;
|
|
125
|
+
};
|
|
126
|
+
approvals: {
|
|
127
|
+
/** Asks the subject's human to approve `action`. The subject is an agent. */
|
|
128
|
+
request(spec: {
|
|
129
|
+
action: Action;
|
|
130
|
+
need: Need;
|
|
131
|
+
}): Promise<ApprovalCreated>;
|
|
132
|
+
};
|
|
133
|
+
sessions: {
|
|
134
|
+
/** The live sessions of the subject's user, as a tree. */
|
|
135
|
+
tree(): Promise<Session[]>;
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** A client of one tensile-auth server. */
|
|
139
|
+
export interface Tensile {
|
|
140
|
+
readonly options: Readonly<TensileOptions>;
|
|
141
|
+
/** The `approvalWait` in effect, in seconds: the option, or its default for this platform. */
|
|
142
|
+
readonly approvalWait: number;
|
|
143
|
+
/** The cache's state, when `cache` is on. */
|
|
144
|
+
readonly cache?: CacheState;
|
|
145
|
+
/** Stops the cache's event stream. A client without a cache has nothing to stop. */
|
|
146
|
+
close(): void;
|
|
147
|
+
/**
|
|
148
|
+
* Authenticates a credential, applies a need, and redeems an approval.
|
|
149
|
+
* A refusal is data: it returns `{allowed: false, problem}` and throws
|
|
150
|
+
* only a `TensileError`, for an outage or a bad app key.
|
|
151
|
+
*/
|
|
152
|
+
check(input: CheckInput): Promise<CheckResult>;
|
|
153
|
+
/** The server's version, API versions, and preset. */
|
|
154
|
+
meta(): Promise<Meta>;
|
|
155
|
+
users: {
|
|
156
|
+
/** The summary of a user, or `undefined` when the server doesn't know the ID. */
|
|
157
|
+
get(id: string): Promise<User | undefined>;
|
|
158
|
+
};
|
|
159
|
+
/** Calls on a person's behalf: `subject` is their credential, or a request that carries it. */
|
|
160
|
+
as(subject: Credential | Request): Subject;
|
|
161
|
+
/** The proxy for the browser routes, as a Fetch API handler. `/auth/` is always on; turn the other groups on in `routes`. */
|
|
162
|
+
proxy(routes?: ProxyRoutes & {
|
|
163
|
+
timeoutMs?: number;
|
|
164
|
+
claimTimeoutMs?: number;
|
|
165
|
+
}): ProxyHandler;
|
|
166
|
+
webhooks: {
|
|
167
|
+
/** Checks a webhook's or hook's Standard Webhooks signature and returns its event. Throws `WebhookError`. */
|
|
168
|
+
verify(request: Request, options?: Omit<WebhookOptions, 'secret'>): Promise<WebhookEvent>;
|
|
169
|
+
/** Answers a hook such as `sign_up`, signed for its `webhook-id` with `webhookSecret`, as the server requires. */
|
|
170
|
+
answer(event: WebhookEvent, answer: HookAnswer): Promise<Response>;
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/** Creates a client of the server at `options.url`. */
|
|
174
|
+
export declare function createTensile(options: TensileOptions): Tensile;
|
|
175
|
+
/** Turns a need into its wire form: `within` becomes `within_seconds`. */
|
|
176
|
+
export declare function wireNeed(n: Need): WireNeed;
|
|
177
|
+
/** Parses seconds, or a duration such as `'90s'`, `'10m'`, or `'1h30m'`, into whole seconds. */
|
|
178
|
+
export declare function seconds(d: number | string): number;
|
|
179
|
+
/** The most seconds the server holds a check for an approval. */
|
|
180
|
+
export declare const maxApprovalWait = 60;
|
|
181
|
+
/**
|
|
182
|
+
* Parses an approval wait: seconds from 0 to 60, or a duration such as
|
|
183
|
+
* `'25s'`. Throws a `RangeError` for anything else, naming `what`.
|
|
184
|
+
*/
|
|
185
|
+
export declare function waitSeconds(d: number | string, what?: string): number;
|
|
186
|
+
/**
|
|
187
|
+
* Returns the wait that a `Prefer` header asks for, as `wait=<seconds>`
|
|
188
|
+
* (RFC 7240), at most 60 seconds, or 0 when it asks for none or the value
|
|
189
|
+
* isn't a positive whole number. Only the first wait preference counts,
|
|
190
|
+
* as in `authhttp`.
|
|
191
|
+
*/
|
|
192
|
+
export declare function preferWait(header: string | null | undefined): number;
|
|
193
|
+
/** Whether the process runs on a serverless platform, where `approvalWait` defaults to 0. */
|
|
194
|
+
export declare function onServerless(env?: Record<string, string | undefined>): boolean;
|
|
195
|
+
/**
|
|
196
|
+
* Reads the credential of a request, as `authhttp.Middleware` does: the
|
|
197
|
+
* `Authorization` header first, with `DPoP` for the DPoP scheme, then the
|
|
198
|
+
* `__Host-session` cookie. Returns `undefined` when there is none.
|
|
199
|
+
*/
|
|
200
|
+
export declare function credentialOf(req: {
|
|
201
|
+
headers: Headers;
|
|
202
|
+
}): Credential | undefined;
|
|
203
|
+
/**
|
|
204
|
+
* Describes a request for `check`: its method, URL, client address, user
|
|
205
|
+
* agent, and the headers cross-origin protection reads. The address is
|
|
206
|
+
* only the `clientIp` given: it never reads `X-Forwarded-For` or
|
|
207
|
+
* `X-Real-IP`, which any client can send. Use `clientIpReader` with the
|
|
208
|
+
* proxies you trust.
|
|
209
|
+
*/
|
|
210
|
+
export declare function requestInfo(req: Request, clientIp?: string): CheckRequestInfo;
|
|
211
|
+
/** Returns the value of cookie `name` in a `Cookie` header. */
|
|
212
|
+
export declare function readCookie(header: string | null | undefined, name: string): string | undefined;
|
|
213
|
+
/** The problem a request without a credential gets, without calling the server. */
|
|
214
|
+
export declare const signedOut: CheckResult;
|
|
215
|
+
/** Encodes a subject for the `Tensile-Subject` header of a GET: base64url of its JSON. */
|
|
216
|
+
export declare function encodeSubject(c: Credential): string;
|
|
217
|
+
/** Compares two versions such as `0.1.0` and `v0.2.0-rc.1`, ignoring pre-release parts. */
|
|
218
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
219
|
+
export { problem, ProblemError, serverURL, type Problem };
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// The core client: createTensile, check, calls on a person's behalf,
|
|
2
|
+
// the meta check, and transport safety.
|
|
3
|
+
import { problem, ProblemError, readProblem, unauthenticated } from "./problem.js";
|
|
4
|
+
import { BodyTooLargeError, readJSON } from "./body.js";
|
|
5
|
+
import { cacheKey, CheckCache, watchEvents } from "./cache.js";
|
|
6
|
+
import { createProxy } from "./proxy.js";
|
|
7
|
+
import { serverURL } from "./transport.js";
|
|
8
|
+
import { answerHook, verifyWebhook } from "./webhooks.js";
|
|
9
|
+
/** The SDK's version, sent as `Tensile-Auth-SDK`. It is the version of the Go module, the image, and the browser client. */
|
|
10
|
+
export const sdkVersion = '0.4.1';
|
|
11
|
+
/** The API version the SDK was written against. */
|
|
12
|
+
export const apiVersion = 'v1';
|
|
13
|
+
/** The name of the session cookie. */
|
|
14
|
+
export const sessionCookie = '__Host-session';
|
|
15
|
+
/** A call that the server couldn't decide: an outage, a bad or throttled app key, or a malformed call. */
|
|
16
|
+
export class TensileError extends Error {
|
|
17
|
+
kind;
|
|
18
|
+
status;
|
|
19
|
+
problem;
|
|
20
|
+
retryAfter;
|
|
21
|
+
constructor(kind, message, o = {}) {
|
|
22
|
+
super(message, { cause: o.cause });
|
|
23
|
+
this.name = 'TensileError';
|
|
24
|
+
this.kind = kind;
|
|
25
|
+
this.status = o.status;
|
|
26
|
+
this.problem = o.problem;
|
|
27
|
+
this.retryAfter = o.retryAfter;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Creates a client of the server at `options.url`. */
|
|
31
|
+
export function createTensile(options) {
|
|
32
|
+
const base = serverURL(options.url);
|
|
33
|
+
if (!options.appKey)
|
|
34
|
+
throw new TypeError('tensile: appKey is required');
|
|
35
|
+
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
36
|
+
const timeoutMs = options.timeoutMs ?? 5000;
|
|
37
|
+
const warn = options.warn ?? ((m) => console.warn(m));
|
|
38
|
+
const approvalWait = options.approvalWait === undefined ? (onServerless() ? 0 : 50) : waitSeconds(options.approvalWait, 'approvalWait');
|
|
39
|
+
const seen = new Map();
|
|
40
|
+
let metaChecked = false;
|
|
41
|
+
async function send(method, path, init = {}) {
|
|
42
|
+
if (!metaChecked) {
|
|
43
|
+
metaChecked = true;
|
|
44
|
+
if (path !== '/v1/meta')
|
|
45
|
+
void checkMeta();
|
|
46
|
+
}
|
|
47
|
+
const headers = {
|
|
48
|
+
'tensile-app-key': options.appKey,
|
|
49
|
+
'tensile-auth-sdk': sdkVersion,
|
|
50
|
+
accept: 'application/json',
|
|
51
|
+
...init.headers,
|
|
52
|
+
};
|
|
53
|
+
if (init.body !== undefined)
|
|
54
|
+
headers['content-type'] = 'application/json';
|
|
55
|
+
const timeout = AbortSignal.timeout(init.timeoutMs ?? timeoutMs);
|
|
56
|
+
try {
|
|
57
|
+
return await fetchFn(new URL(path, base), {
|
|
58
|
+
method,
|
|
59
|
+
headers,
|
|
60
|
+
body: init.body === undefined ? undefined : JSON.stringify(init.body),
|
|
61
|
+
redirect: 'manual',
|
|
62
|
+
signal: init.signal ? AbortSignal.any([timeout, init.signal]) : timeout,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
if (init.signal?.aborted)
|
|
67
|
+
throw init.signal.reason;
|
|
68
|
+
throw new TensileError('outage', `tensile: ${method} ${path} failed: ${err.message}`, { cause: err });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// failure turns a response that isn't a decision into a TensileError.
|
|
72
|
+
async function failure(res, path) {
|
|
73
|
+
const p = await readProblem(res);
|
|
74
|
+
const msg = `tensile: ${path} answered ${res.status} ${p.code}`;
|
|
75
|
+
switch (res.status) {
|
|
76
|
+
case 401: return new TensileError('app_key', `${msg}: check the app key`, { status: 401, problem: p });
|
|
77
|
+
case 429: return new TensileError('throttled', msg, { status: 429, problem: p, retryAfter: Number(res.headers.get('retry-after')) || p.retry_after });
|
|
78
|
+
case 404: return new TensileError('no_v1', `${msg}: the server doesn't serve ${apiVersion}`, { status: 404, problem: p });
|
|
79
|
+
case 400: return new TensileError('bad_request', msg, { status: 400, problem: p });
|
|
80
|
+
default: return new TensileError('outage', msg, { status: res.status, problem: p });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// answer reads a server answer, at most 1 MiB of it; a larger or broken
|
|
84
|
+
// answer is an outage, never a decision.
|
|
85
|
+
async function answer(res, path) {
|
|
86
|
+
try {
|
|
87
|
+
return await readJSON(res);
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
const why = err instanceof BodyTooLargeError ? 'an answer larger than 1 MiB' : 'an answer that is not JSON';
|
|
91
|
+
throw new TensileError('outage', `tensile: ${path} sent ${why}`, { status: res.status, cause: err });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function checkMeta() {
|
|
95
|
+
try {
|
|
96
|
+
const m = await meta();
|
|
97
|
+
if (!m.api_versions.includes(apiVersion))
|
|
98
|
+
warn(`tensile: the server doesn't serve ${apiVersion}; it serves ${m.api_versions.join(', ')}`);
|
|
99
|
+
else if (compareVersions(m.version, sdkVersion) < 0)
|
|
100
|
+
warn(`tensile: the server is ${m.version}, older than the SDK's ${sdkVersion}; upgrade the server`);
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
if (err instanceof TensileError && err.kind === 'no_v1')
|
|
104
|
+
warn(err.message);
|
|
105
|
+
// Other failures surface on the calls themselves.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function meta() {
|
|
109
|
+
const res = await send('GET', '/v1/meta');
|
|
110
|
+
if (res.status !== 200)
|
|
111
|
+
throw await failure(res, '/v1/meta');
|
|
112
|
+
return answer(res, '/v1/meta');
|
|
113
|
+
}
|
|
114
|
+
async function firstSeen(p) {
|
|
115
|
+
if (!options.onFirstSeen || !p.user)
|
|
116
|
+
return;
|
|
117
|
+
let run = seen.get(p.user);
|
|
118
|
+
if (!run) {
|
|
119
|
+
if (seen.size >= 100_000)
|
|
120
|
+
seen.clear();
|
|
121
|
+
run = Promise.resolve().then(() => options.onFirstSeen(p));
|
|
122
|
+
seen.set(p.user, run);
|
|
123
|
+
run.catch(() => seen.delete(p.user));
|
|
124
|
+
}
|
|
125
|
+
await run;
|
|
126
|
+
}
|
|
127
|
+
const cache = options.cache ? new CheckCache(options.cache === true ? {} : options.cache) : undefined;
|
|
128
|
+
const stopWatching = cache
|
|
129
|
+
? watchEvents({
|
|
130
|
+
url: new URL('/v1/events/stream', base), fetch: fetchFn, cache, warn,
|
|
131
|
+
headers: { 'tensile-app-key': options.appKey, 'tensile-auth-sdk': sdkVersion },
|
|
132
|
+
})
|
|
133
|
+
: () => { };
|
|
134
|
+
async function check(input) {
|
|
135
|
+
const credential = onlyCredential(input.credential);
|
|
136
|
+
const body = { credential, request: input.request };
|
|
137
|
+
if (input.need)
|
|
138
|
+
body.need = wireNeed(input.need);
|
|
139
|
+
let wait = 0;
|
|
140
|
+
if (input.approval) {
|
|
141
|
+
const { id, action } = input.approval;
|
|
142
|
+
body.approval = id ? { id, action } : { action };
|
|
143
|
+
wait = clampWait(input.approval.wait);
|
|
144
|
+
}
|
|
145
|
+
if (input.resource)
|
|
146
|
+
body.resource = input.resource;
|
|
147
|
+
const generation = cache?.generation ?? 0;
|
|
148
|
+
const key = cache?.active ? await cacheKey(body) : undefined;
|
|
149
|
+
const hit = key ? cache.get(key) : undefined;
|
|
150
|
+
if (hit) {
|
|
151
|
+
await firstSeen(hit.principal);
|
|
152
|
+
return hit;
|
|
153
|
+
}
|
|
154
|
+
// A waiting redeem may take the whole wait before the server answers.
|
|
155
|
+
const held = body.approval?.id ? wait * 1000 : 0;
|
|
156
|
+
let out;
|
|
157
|
+
try {
|
|
158
|
+
const res = await send('POST', '/v1/check', {
|
|
159
|
+
body, signal: input.signal, timeoutMs: timeoutMs + held, ...(wait > 0 ? { headers: { prefer: `wait=${wait}` } } : {}),
|
|
160
|
+
});
|
|
161
|
+
if (res.status !== 200)
|
|
162
|
+
throw await failure(res, '/v1/check');
|
|
163
|
+
out = await answer(res, '/v1/check');
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
if (input.signal?.aborted)
|
|
167
|
+
throw input.signal.reason;
|
|
168
|
+
throw err;
|
|
169
|
+
}
|
|
170
|
+
out.set_cookies ??= [];
|
|
171
|
+
out.headers ??= {};
|
|
172
|
+
if (key)
|
|
173
|
+
cache.set(key, out, generation);
|
|
174
|
+
if (out.allowed)
|
|
175
|
+
await firstSeen(out.principal);
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
// personal runs a call for a subject: a refusal throws ProblemError,
|
|
179
|
+
// and a failure to decide throws TensileError.
|
|
180
|
+
async function personal(method, path, subject, body) {
|
|
181
|
+
const res = body === undefined
|
|
182
|
+
? await send(method, path, { headers: { 'tensile-subject': encodeSubject(subject) } })
|
|
183
|
+
: await send(method, path, { body: { subject, ...body } });
|
|
184
|
+
if (res.ok)
|
|
185
|
+
return answer(res, path);
|
|
186
|
+
// A bare 404 means the server doesn't serve the route at all.
|
|
187
|
+
if (res.status === 404 && !isProblem(res))
|
|
188
|
+
throw await failure(res, path);
|
|
189
|
+
if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 409 || res.status === 422) {
|
|
190
|
+
const p = await readProblem(res);
|
|
191
|
+
// A bad app key answers app_key_invalid; any other 401 is about the
|
|
192
|
+
// subject's credential.
|
|
193
|
+
if (res.status === 401 && p.code === 'app_key_invalid')
|
|
194
|
+
throw new TensileError('app_key', `tensile: ${path}: check the app key`, { status: 401, problem: p });
|
|
195
|
+
throw new ProblemError(p);
|
|
196
|
+
}
|
|
197
|
+
if (res.status === 400)
|
|
198
|
+
throw new ProblemError(await readProblem(res));
|
|
199
|
+
throw await failure(res, path);
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
options: Object.freeze({ ...options }),
|
|
203
|
+
approvalWait,
|
|
204
|
+
...(cache ? { cache } : {}),
|
|
205
|
+
close: stopWatching,
|
|
206
|
+
check,
|
|
207
|
+
meta,
|
|
208
|
+
users: {
|
|
209
|
+
async get(id) {
|
|
210
|
+
const path = `/v1/users/${encodeURIComponent(id)}`;
|
|
211
|
+
const res = await send('GET', path);
|
|
212
|
+
// A problem means the server doesn't know the user; a bare 404
|
|
213
|
+
// means it doesn't serve the API at all.
|
|
214
|
+
if (res.status === 404 && isProblem(res))
|
|
215
|
+
return undefined;
|
|
216
|
+
if (res.status !== 200)
|
|
217
|
+
throw await failure(res, path);
|
|
218
|
+
return answer(res, path);
|
|
219
|
+
},
|
|
220
|
+
},
|
|
221
|
+
as(subject) {
|
|
222
|
+
const credential = subject instanceof Request ? credentialOf(subject) : onlyCredential(subject);
|
|
223
|
+
if (!credential)
|
|
224
|
+
throw new ProblemError(unauthenticated);
|
|
225
|
+
return {
|
|
226
|
+
agents: {
|
|
227
|
+
create: spec => personal('POST', '/v1/agents', credential, { name: spec.name, scopes: spec.scopes }),
|
|
228
|
+
delegate: (id, spec) => personal('POST', `/v1/agents/${encodeURIComponent(id)}/delegate`, credential, {
|
|
229
|
+
scopes: spec.scopes,
|
|
230
|
+
...(spec.name ? { name: spec.name } : {}),
|
|
231
|
+
...(spec.ttl !== undefined ? { ttl_seconds: seconds(spec.ttl) } : {}),
|
|
232
|
+
...(spec.keyThumbprint ? { key_thumbprint: spec.keyThumbprint } : {}),
|
|
233
|
+
}),
|
|
234
|
+
},
|
|
235
|
+
approvals: {
|
|
236
|
+
request: spec => personal('POST', '/v1/approvals', credential, { action: spec.action, need: wireNeed(spec.need) }),
|
|
237
|
+
},
|
|
238
|
+
sessions: {
|
|
239
|
+
tree: async () => (await personal('GET', '/v1/sessions/tree', credential)).sessions,
|
|
240
|
+
},
|
|
241
|
+
};
|
|
242
|
+
},
|
|
243
|
+
proxy: (routes = {}) => createProxy({ ...routes, url: options.url, appKey: options.appKey, fetch: options.fetch }),
|
|
244
|
+
webhooks: {
|
|
245
|
+
verify(request, o = {}) {
|
|
246
|
+
if (!options.webhookSecret)
|
|
247
|
+
throw new TypeError('tensile: set webhookSecret to verify webhooks');
|
|
248
|
+
return verifyWebhook(request, { ...o, secret: options.webhookSecret });
|
|
249
|
+
},
|
|
250
|
+
answer(event, answer) {
|
|
251
|
+
if (!options.webhookSecret)
|
|
252
|
+
throw new TypeError('tensile: set webhookSecret to answer hooks');
|
|
253
|
+
return answerHook(event, answer, { secret: options.webhookSecret });
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/** Turns a need into its wire form: `within` becomes `within_seconds`. */
|
|
259
|
+
export function wireNeed(n) {
|
|
260
|
+
if (!n.action)
|
|
261
|
+
throw new TypeError('tensile: a need has an action');
|
|
262
|
+
const w = { action: n.action };
|
|
263
|
+
if (n.human)
|
|
264
|
+
w.human = true;
|
|
265
|
+
if (n.assurance)
|
|
266
|
+
w.assurance = n.assurance;
|
|
267
|
+
if (n.within !== undefined)
|
|
268
|
+
w.within_seconds = seconds(n.within);
|
|
269
|
+
if (n.scopes?.length)
|
|
270
|
+
w.scopes = [...n.scopes];
|
|
271
|
+
if (n.approvalTtl !== undefined) {
|
|
272
|
+
const ttl = seconds(n.approvalTtl);
|
|
273
|
+
if (ttl < 60 || ttl > 86_400)
|
|
274
|
+
throw new RangeError(`tensile: approvalTtl must be 1 minute to 24 hours, not ${ttl} seconds`);
|
|
275
|
+
w.approval_ttl_seconds = ttl;
|
|
276
|
+
}
|
|
277
|
+
return w;
|
|
278
|
+
}
|
|
279
|
+
/** Parses seconds, or a duration such as `'90s'`, `'10m'`, or `'1h30m'`, into whole seconds. */
|
|
280
|
+
export function seconds(d) {
|
|
281
|
+
if (typeof d === 'number') {
|
|
282
|
+
if (!Number.isFinite(d) || d <= 0)
|
|
283
|
+
throw new RangeError(`tensile: duration ${d} must be positive`);
|
|
284
|
+
return Math.ceil(d);
|
|
285
|
+
}
|
|
286
|
+
const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(d.trim());
|
|
287
|
+
if (!m || d.trim() === '')
|
|
288
|
+
throw new RangeError(`tensile: duration ${JSON.stringify(d)} isn't like '10m' or '1h30m'`);
|
|
289
|
+
const s = Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
|
|
290
|
+
if (s <= 0)
|
|
291
|
+
throw new RangeError(`tensile: duration ${JSON.stringify(d)} must be positive`);
|
|
292
|
+
return s;
|
|
293
|
+
}
|
|
294
|
+
/** The most seconds the server holds a check for an approval. */
|
|
295
|
+
export const maxApprovalWait = 60;
|
|
296
|
+
/**
|
|
297
|
+
* Parses an approval wait: seconds from 0 to 60, or a duration such as
|
|
298
|
+
* `'25s'`. Throws a `RangeError` for anything else, naming `what`.
|
|
299
|
+
*/
|
|
300
|
+
export function waitSeconds(d, what = 'wait') {
|
|
301
|
+
const s = typeof d === 'number' ? d : /^\s*0+s?\s*$/.test(d) ? 0 : seconds(d);
|
|
302
|
+
if (!Number.isFinite(s) || s < 0 || s > maxApprovalWait)
|
|
303
|
+
throw new RangeError(`tensile: ${what} must be 0 to ${maxApprovalWait} seconds, not ${JSON.stringify(d)}`);
|
|
304
|
+
return Math.ceil(s);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Returns the wait that a `Prefer` header asks for, as `wait=<seconds>`
|
|
308
|
+
* (RFC 7240), at most 60 seconds, or 0 when it asks for none or the value
|
|
309
|
+
* isn't a positive whole number. Only the first wait preference counts,
|
|
310
|
+
* as in `authhttp`.
|
|
311
|
+
*/
|
|
312
|
+
export function preferWait(header) {
|
|
313
|
+
if (!header)
|
|
314
|
+
return 0;
|
|
315
|
+
for (const part of header.split(',')) {
|
|
316
|
+
const pref = part.split(';')[0];
|
|
317
|
+
const i = pref.indexOf('=');
|
|
318
|
+
if (i < 0 || pref.slice(0, i).trim().toLowerCase() !== 'wait')
|
|
319
|
+
continue;
|
|
320
|
+
const v = pref.slice(i + 1).trim().replace(/^"|"$/g, '');
|
|
321
|
+
if (!/^\+?\d+$/.test(v))
|
|
322
|
+
return 0;
|
|
323
|
+
const n = Number(v);
|
|
324
|
+
return n > 0 ? Math.min(n, maxApprovalWait) : 0;
|
|
325
|
+
}
|
|
326
|
+
return 0;
|
|
327
|
+
}
|
|
328
|
+
/** Whether the process runs on a serverless platform, where `approvalWait` defaults to 0. */
|
|
329
|
+
export function onServerless(env = typeof process === 'undefined' ? {} : process.env) {
|
|
330
|
+
if (typeof globalThis.EdgeRuntime !== 'undefined' || env.NEXT_RUNTIME === 'edge')
|
|
331
|
+
return true;
|
|
332
|
+
return Boolean(env.VERCEL || env.AWS_LAMBDA_FUNCTION_NAME || env.NETLIFY);
|
|
333
|
+
}
|
|
334
|
+
function clampWait(n) {
|
|
335
|
+
if (n === undefined || !Number.isFinite(n) || n <= 0)
|
|
336
|
+
return 0;
|
|
337
|
+
return Math.min(Math.floor(n), maxApprovalWait);
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Reads the credential of a request, as `authhttp.Middleware` does: the
|
|
341
|
+
* `Authorization` header first, with `DPoP` for the DPoP scheme, then the
|
|
342
|
+
* `__Host-session` cookie. Returns `undefined` when there is none.
|
|
343
|
+
*/
|
|
344
|
+
export function credentialOf(req) {
|
|
345
|
+
const authorization = req.headers.get('authorization');
|
|
346
|
+
if (authorization) {
|
|
347
|
+
const dpop = req.headers.get('dpop');
|
|
348
|
+
return /^dpop\s/i.test(authorization) && dpop ? { authorization, dpop } : { authorization };
|
|
349
|
+
}
|
|
350
|
+
const cookie = readCookie(req.headers.get('cookie'), sessionCookie);
|
|
351
|
+
return cookie ? { cookie } : undefined;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Describes a request for `check`: its method, URL, client address, user
|
|
355
|
+
* agent, and the headers cross-origin protection reads. The address is
|
|
356
|
+
* only the `clientIp` given: it never reads `X-Forwarded-For` or
|
|
357
|
+
* `X-Real-IP`, which any client can send. Use `clientIpReader` with the
|
|
358
|
+
* proxies you trust.
|
|
359
|
+
*/
|
|
360
|
+
export function requestInfo(req, clientIp) {
|
|
361
|
+
const info = { method: req.method, url: req.url };
|
|
362
|
+
if (clientIp)
|
|
363
|
+
info.client_ip = clientIp;
|
|
364
|
+
const ua = req.headers.get('user-agent');
|
|
365
|
+
if (ua)
|
|
366
|
+
info.user_agent = ua;
|
|
367
|
+
const origin = req.headers.get('origin');
|
|
368
|
+
if (origin)
|
|
369
|
+
info.origin = origin;
|
|
370
|
+
const site = req.headers.get('sec-fetch-site');
|
|
371
|
+
if (site)
|
|
372
|
+
info.sec_fetch_site = site;
|
|
373
|
+
return info;
|
|
374
|
+
}
|
|
375
|
+
/** Returns the value of cookie `name` in a `Cookie` header. */
|
|
376
|
+
export function readCookie(header, name) {
|
|
377
|
+
if (!header)
|
|
378
|
+
return undefined;
|
|
379
|
+
for (const part of header.split(';')) {
|
|
380
|
+
const i = part.indexOf('=');
|
|
381
|
+
if (i < 0)
|
|
382
|
+
continue;
|
|
383
|
+
if (part.slice(0, i).trim() === name)
|
|
384
|
+
return part.slice(i + 1).trim();
|
|
385
|
+
}
|
|
386
|
+
return undefined;
|
|
387
|
+
}
|
|
388
|
+
/** The problem a request without a credential gets, without calling the server. */
|
|
389
|
+
export const signedOut = { allowed: false, problem: unauthenticated, set_cookies: [], headers: {} };
|
|
390
|
+
function isProblem(res) {
|
|
391
|
+
return (res.headers.get('content-type') ?? '').startsWith('application/problem+json');
|
|
392
|
+
}
|
|
393
|
+
function onlyCredential(c) {
|
|
394
|
+
const n = Number(Boolean(c?.cookie)) + Number(Boolean(c?.authorization));
|
|
395
|
+
if (n !== 1)
|
|
396
|
+
throw new TypeError('tensile: a credential holds exactly one of cookie or authorization');
|
|
397
|
+
if (c.cookie)
|
|
398
|
+
return { cookie: c.cookie };
|
|
399
|
+
return c.dpop ? { authorization: c.authorization, dpop: c.dpop } : { authorization: c.authorization };
|
|
400
|
+
}
|
|
401
|
+
/** Encodes a subject for the `Tensile-Subject` header of a GET: base64url of its JSON. */
|
|
402
|
+
export function encodeSubject(c) {
|
|
403
|
+
const bytes = new TextEncoder().encode(JSON.stringify(c));
|
|
404
|
+
let bin = '';
|
|
405
|
+
for (const b of bytes)
|
|
406
|
+
bin += String.fromCharCode(b);
|
|
407
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
408
|
+
}
|
|
409
|
+
/** Compares two versions such as `0.1.0` and `v0.2.0-rc.1`, ignoring pre-release parts. */
|
|
410
|
+
export function compareVersions(a, b) {
|
|
411
|
+
const parse = (v) => v.replace(/^v/, '').split(/[-+]/)[0].split('.').map(n => Number(n) || 0);
|
|
412
|
+
const [x, y] = [parse(a), parse(b)];
|
|
413
|
+
for (let i = 0; i < 3; i++) {
|
|
414
|
+
const d = (x[i] ?? 0) - (y[i] ?? 0);
|
|
415
|
+
if (d)
|
|
416
|
+
return Math.sign(d);
|
|
417
|
+
}
|
|
418
|
+
return 0;
|
|
419
|
+
}
|
|
420
|
+
export { problem, ProblemError, serverURL };
|