@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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,143 @@
1
- # Temporary Holding Version
1
+ # @tensile-tools/auth
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The backend SDK of the tensile-auth server. A Node, Bun, or Deno app uses it to check each request with the server in one call, to act for a person, and to verify webhooks. It has no runtime dependencies: it uses only `fetch`, Web Crypto, and Web Streams.
4
+
5
+ It is versioned with the Go library:
6
+
7
+ ```sh
8
+ npm install @tensile-tools/auth @tensile-tools/auth-client
9
+ ```
10
+
11
+ ## Use it with Next.js
12
+
13
+ ```ts
14
+ // lib/auth.ts
15
+ import { tensile } from '@tensile-tools/auth/next'
16
+ export const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY!, signIn: '/sign-in' })
17
+
18
+ // app/auth/[...path]/route.ts
19
+ import { auth } from '@/lib/auth'
20
+ export const { GET, POST } = auth.proxy
21
+
22
+ // app/settings/page.tsx (imports auth the same way)
23
+ export default async function Settings() {
24
+ const p = await auth.require({ action: 'settings.view', human: true })
25
+ return <SettingsForm user={await db.user.findUniqueOrThrow({ where: { authUserId: p.user } })} />
26
+ }
27
+ ```
28
+
29
+ The browser talks to the app's own origin: the proxy route forwards `/auth/*` to the server, so sessions stay in `__Host-` cookies and the [browser client](../client/README.md) works unchanged. Every page or handler checks its need with the server, which decides, records, and explains. See [`examples/next`](examples/next/README.md) for the whole app.
30
+
31
+ ## Use it without a framework
32
+
33
+ ```ts
34
+ import { createTensile } from '@tensile-tools/auth'
35
+
36
+ const auth = createTensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
37
+
38
+ const r = await auth.check({
39
+ credential: { cookie: sessionCookieValue },
40
+ request: { method: 'DELETE', url: 'https://app.example.com/repos/7', client_ip: ip },
41
+ need: { action: 'repo.delete', human: true, assurance: 'multi', within: '10m' },
42
+ })
43
+ if (!r.allowed) return problemResponse(r.problem)
44
+ ```
45
+
46
+ - `check({credential, request, need?, approval?, resource?, signal?})` calls `POST /v1/check`. It returns `{allowed: true, principal}` or `{allowed: false, problem}`, with `set_cookies` and `headers` to copy onto the app's response. It never throws for a refusal. It throws a `TensileError` only when the server can't decide: an outage, a timeout, or a bad or throttled app key. Answer those with 503, never 401.
47
+ - `credentialOf(request)` reads a request's credential as `authhttp.Middleware` does: `Authorization` first, with `DPoP` for the DPoP scheme, then the `__Host-session` cookie.
48
+ - `requestInfo(request, clientIp)` describes a request for `check`.
49
+ - `as(subject).agents.create`, `.agents.delegate`, `.approvals.request`, and `.sessions.tree` act for a person. `subject` is that person's credential, or a request that carries it: the app key alone never acts for anyone. A refusal throws a `ProblemError`.
50
+ - `users.get(id)` returns a user's summary, `{id, email, email_verified, live_sessions, agents, last_seen_at}`, or `undefined`.
51
+ - `meta()` returns the server's version. The first call to the server also checks it, and warns when the server is older than the SDK.
52
+ - `webhooks.verify(request)` checks a Standard Webhooks signature with `webhookSecret`, refuses a timestamp more than 5 minutes from now, and returns the event. Hooks such as `sign_up` are signed the same way.
53
+ - `webhooks.answer(event, answer)` answers a hook, `sign_up` with `{allow, user_id?}` or `session_scopes` with `{scopes}`, signed for the hook's own `webhook-id`. The server refuses an answer without that signature and fails closed: a sign-up gets 503, and a session gets no scopes.
54
+ - `proxy(routes)` returns the proxy for the browser routes, a Fetch API handler. It forwards `/auth/`, and `/admin/`, `/login/oauth/`, `/login/device/`, and `/.well-known/` only when `routes` turns them on. It forwards only the library's cookies and a fixed set of headers, adds the app key and the client's address, never returns the app key, and caps request bodies at 1 MiB.
55
+ - `onFirstSeen(principal)` runs the first time the process sees a user ID, before the request continues, so the app can create its own row for that user.
56
+
57
+ `createTensile` refuses an `http://` server URL unless the host is loopback, a private address, or a single-label name such as `tensile-auth` on a Compose network. Every call has a 5-second timeout, set with `timeoutMs`, and `check` never retries; a check that waits for an approval gets its wait on top. The proxy waits up to 30 seconds for the `/auth/` routes, and up to 65 seconds for `/auth/claims/`, which long-polls for up to 60 seconds.
58
+
59
+ ## Wait for an approval
60
+
61
+ An agent that an approvable route refuses gets an approval and retries with `Tensile-Approval: <id>`. With `Prefer: wait=N` on the retry, the route holds the request until the person approves or denies, and runs once, so the agent doesn't poll. The server holds the app's check call, so the app keeps no state between the two requests.
62
+
63
+ `approvalWait`, in seconds from 0 to 60 or a duration such as `'25s'`, caps the wait and is the wait the refusal offers in `wait_hint`:
64
+
65
+ | Where the app runs | Default | Why |
66
+ |---|---|---|
67
+ | A long-running server | 50 | Under the common 60-second idle timeout of load balancers |
68
+ | A detected serverless platform: `VERCEL`, `AWS_LAMBDA_FUNCTION_NAME`, `NETLIFY`, or an edge runtime | 0 | The SDK can't read the function's limit, and a function stopped mid-wait can spend the approval without running the route. The agent retries after `Retry-After` instead |
69
+
70
+ On serverless, turn waiting on with the function's limit, and keep `maxDuration >= approvalWait + 5`:
71
+
72
+ ```ts
73
+ // app/api/repos/[id]/route.ts, on Vercel
74
+ export const maxDuration = 30
75
+ export const DELETE = auth.approvable(need, describe, handler, { wait: 25 })
76
+ ```
77
+
78
+ - The wait is the smallest of the agent's `Prefer`, the route's `wait` or `approvalWait`, 60 seconds, and the approval's remaining life. A retry without `Prefer` doesn't wait.
79
+ - `approvable` in each adapter takes `{ wait }` to replace `approvalWait` for one route. `auth.approvalWait` reports the value in effect.
80
+ - A waiting check's timeout is its wait plus `timeoutMs`, so a wait that runs out is `approval_pending` with `Retry-After`, never a `TensileError`.
81
+ - The check ends when the agent disconnects. Express builds the signal from the response's `close` event; Hono and Next.js use `req.signal`. Without an adapter, pass `signal` and `approval.wait` to `check`.
82
+ - The server holds at most 4 waits for each agent and 256 for each app key on each replica; over either, the retry answers at once. A server older than this ignores `Prefer` and answers at once.
83
+
84
+ ## Cache checks
85
+
86
+ Every `check` calls the server by default, so a revocation applies to the next request. A long-running process can cache allowed answers instead:
87
+
88
+ ```ts
89
+ const auth = createTensile({ url, appKey, cache: true })
90
+ ```
91
+
92
+ The cache follows the server's own cache rules:
93
+
94
+ - It holds `GET /v1/events/stream` open, and serves nothing until the stream sends `ready`.
95
+ - Each `invalidate` event clears it, so a revocation reaches it within 100 milliseconds. The stream carries no session hashes, so every change clears everything.
96
+ - When the stream ends, fails, or stays silent for 45 seconds, it serves nothing until the next `ready`. It reconnects after 1 second, backing off to 30.
97
+ - It holds only allowed answers that set no cookie, for at most 30 seconds and never past the session's expiry, keyed by the SHA-256 of the credential and the facts the answer depends on.
98
+ - It never caches a DPoP request, an approval, or a need with `within` or `assurance`.
99
+
100
+ Set `cache: { ttlMs, maxEntries }` to hold answers for less time or hold fewer of them. `auth.cache.active` and `auth.cache.size` report its state, and `auth.close()` stops the stream. Leave it off on serverless runtimes, which can't hold a stream.
101
+
102
+ ## Adapters
103
+
104
+ | Import | For |
105
+ |---|---|
106
+ | [`@tensile-tools/auth/next`](next/README.md) | Next.js 16 and later, App Router |
107
+ | [`@tensile-tools/auth/express`](express/README.md) | Express 5 |
108
+ | [`@tensile-tools/auth/hono`](hono/README.md) | Hono 4 |
109
+
110
+ Each adapter has the same parts: a proxy for the browser routes, a principal, a need, an approvable need, and calls on a person's behalf. Its framework is an optional peer dependency.
111
+
112
+ ## Contents
113
+
114
+ | Name | What it holds |
115
+ |---|---|
116
+ | [`src/`](src) | The TypeScript source |
117
+ | [`test/`](test) | The tests and the mock server they run against |
118
+ | [`e2e/`](e2e) | The contract test against the real server, and the software passkey it signs up with |
119
+ | [`next/`](next), [`express/`](express), [`hono/`](hono) | The adapters' READMEs |
120
+ | [`examples/next/`](examples/next) | A Next.js app with Playwright tests against the mock |
121
+ | [`package.json`](package.json), [`package-lock.json`](package-lock.json) | The package and its development dependencies |
122
+ | [`tsconfig.json`](tsconfig.json), [`tsconfig.build.json`](tsconfig.build.json) | The TypeScript settings for the type check and for the build |
123
+
124
+ ## Check it
125
+
126
+ To type-check, test, and build the SDK, run `just sdk`. It needs Node 22.18 or later, which runs TypeScript without a build step.
127
+
128
+ To build the example app and run its Playwright tests, run `just sdk-example`.
129
+
130
+ To check the SDK against the real server, run `just sdk-e2e`. It needs Go, at least 1,500 MB of free disk, and 20% of free memory.
131
+
132
+ ## The contract
133
+
134
+ `src/gen/api.ts` is generated from the server's `server/openapi.json`. To regenerate it after the document changes, run `npm run gen` in `sdk/`. `just sdk` fails when the committed file differs from a fresh generation.
135
+
136
+ `src/api.ts` narrows the generated types, for example `assurance` to its 4 values, and `test/contract.ts` fails the type-check when the SDK sends or reads a field the document lacks.
137
+
138
+ `just sdk-e2e` builds the server, starts it with SQLite, and checks the SDK against it with a real app key and a real passkey sign-up: `/v1/check`, the routes that act for a person, an agent's approval from request to redeem, approval waits, the proxy, the Hono adapter, the cache, and hook answers.
139
+
140
+ ## See also
141
+
142
+ - [The server and SDK design](../docs/design/server.md)
143
+ - [The browser client](../client/README.md)
@@ -0,0 +1,54 @@
1
+ import { type Action, type Need, type Principal, type Tensile } from './core.ts';
2
+ import { type Problem } from './problem.ts';
3
+ /** The header an agent retries with after its human approves. */
4
+ export declare const approvalHeader = "tensile-approval";
5
+ /** What a route asks of the check. */
6
+ export interface Gate {
7
+ need?: Need;
8
+ /** Describes the exact action, so an agent can ask its human to approve it. */
9
+ action?: Action;
10
+ clientIp?: string;
11
+ resource?: string;
12
+ /** Replaces the client's `approvalWait` for this route, in seconds from 0 to 60. */
13
+ wait?: number;
14
+ }
15
+ /** Options of an adapter's `approvable`. */
16
+ export interface ApprovableOptions {
17
+ /**
18
+ * The longest this route holds an agent's retry for the person's
19
+ * decision, in seconds from 0 to 60 or a duration such as `'25s'`.
20
+ * Defaults to the client's `approvalWait`. On serverless, keep the
21
+ * route's `maxDuration` at least this plus 5 seconds.
22
+ */
23
+ wait?: number | string;
24
+ }
25
+ /** The outcome for one request. Copy `setCookies` and `headers` onto the response in every case. */
26
+ export type Decision = {
27
+ kind: 'allowed';
28
+ principal: Principal;
29
+ setCookies: string[];
30
+ headers: Record<string, string>;
31
+ } | {
32
+ kind: 'anonymous';
33
+ setCookies: string[];
34
+ headers: Record<string, string>;
35
+ } | {
36
+ kind: 'refused';
37
+ response: Response;
38
+ problem: Problem;
39
+ };
40
+ /**
41
+ * Decides one request. Without a need, a request with no credential, or
42
+ * with a session cookie the server no longer knows, is anonymous, as in
43
+ * `authhttp.Middleware`; with a need, it is refused. An outage or a bad
44
+ * app key is refused with 503, never 401.
45
+ *
46
+ * With `gate.action`, the check creates or redeems an approval. It offers
47
+ * the agent a wait of the route's `wait`, or the client's `approvalWait`,
48
+ * and on a retry holds the check for the smallest of that and the
49
+ * agent's own `Prefer: wait=N`; without that header it doesn't wait. The
50
+ * check ends when `req.signal` aborts, as when the agent disconnects.
51
+ */
52
+ export declare function decide(auth: Tensile, req: Request, gate?: Gate): Promise<Decision>;
53
+ /** Copies a decision's cookies and headers onto `headers`. */
54
+ export declare function applyTo(headers: Headers, d: Decision): void;
package/dist/adapt.js ADDED
@@ -0,0 +1,72 @@
1
+ // What every adapter does with a request: read its credential, call
2
+ // /v1/check with the route's need and approval, and turn the answer into
3
+ // a principal or a response. Adapters only translate to their framework.
4
+ import { credentialOf, preferWait, requestInfo, TensileError } from "./core.js";
5
+ import { problemResponse, unauthenticated, unavailable } from "./problem.js";
6
+ /** The header an agent retries with after its human approves. */
7
+ export const approvalHeader = 'tensile-approval';
8
+ /**
9
+ * Decides one request. Without a need, a request with no credential, or
10
+ * with a session cookie the server no longer knows, is anonymous, as in
11
+ * `authhttp.Middleware`; with a need, it is refused. An outage or a bad
12
+ * app key is refused with 503, never 401.
13
+ *
14
+ * With `gate.action`, the check creates or redeems an approval. It offers
15
+ * the agent a wait of the route's `wait`, or the client's `approvalWait`,
16
+ * and on a retry holds the check for the smallest of that and the
17
+ * agent's own `Prefer: wait=N`; without that header it doesn't wait. The
18
+ * check ends when `req.signal` aborts, as when the agent disconnects.
19
+ */
20
+ export async function decide(auth, req, gate = {}) {
21
+ const credential = credentialOf(req);
22
+ if (!credential) {
23
+ if (!gate.need)
24
+ return { kind: 'anonymous', setCookies: [], headers: {} };
25
+ return { kind: 'refused', problem: unauthenticated, response: problemResponse(unauthenticated) };
26
+ }
27
+ let r;
28
+ try {
29
+ const approvalId = req.headers.get(approvalHeader) ?? undefined;
30
+ let approval;
31
+ if (gate.action) {
32
+ const cap = gate.wait ?? auth.approvalWait;
33
+ const wait = approvalId ? Math.min(preferWait(req.headers.get('prefer')), cap) : cap;
34
+ approval = { ...(approvalId ? { id: approvalId } : {}), action: gate.action, ...(wait > 0 ? { wait } : {}) };
35
+ }
36
+ r = await auth.check({
37
+ credential,
38
+ request: requestInfo(req, gate.clientIp),
39
+ need: gate.need,
40
+ approval,
41
+ resource: gate.resource,
42
+ signal: req.signal,
43
+ });
44
+ }
45
+ catch (err) {
46
+ // The end user went away: nobody reads the answer.
47
+ if (req.signal?.aborted)
48
+ return { kind: 'refused', problem: unavailable, response: problemResponse(unavailable) };
49
+ if (!(err instanceof TensileError))
50
+ throw err;
51
+ console.error(`tensile: answering 503: ${err.message}`);
52
+ return { kind: 'refused', problem: unavailable, response: problemResponse(unavailable, { headers: { 'retry-after': '5' } }) };
53
+ }
54
+ if (r.allowed)
55
+ return { kind: 'allowed', principal: r.principal, setCookies: r.set_cookies, headers: r.headers };
56
+ if (!gate.need && credential.cookie && r.problem.code === 'unauthenticated') {
57
+ return { kind: 'anonymous', setCookies: r.set_cookies, headers: r.headers };
58
+ }
59
+ const headers = new Headers(r.headers);
60
+ for (const c of r.set_cookies)
61
+ headers.append('set-cookie', c);
62
+ return { kind: 'refused', problem: r.problem, response: problemResponse(r.problem, { headers }) };
63
+ }
64
+ /** Copies a decision's cookies and headers onto `headers`. */
65
+ export function applyTo(headers, d) {
66
+ if (d.kind === 'refused')
67
+ return;
68
+ for (const [k, v] of Object.entries(d.headers))
69
+ headers.set(k, v);
70
+ for (const c of d.setCookies)
71
+ headers.append('set-cookie', c);
72
+ }
package/dist/api.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { components } from './gen/api.ts';
2
+ import type { Assurance, Problem } from './problem.ts';
3
+ type G = components['schemas'];
4
+ /**
5
+ * Exactly one credential: the `__Host-session` cookie's value, or the
6
+ * request's `Authorization` header, with the `DPoP` header when the scheme
7
+ * is DPoP.
8
+ */
9
+ export type Credential = {
10
+ cookie: string;
11
+ authorization?: never;
12
+ dpop?: never;
13
+ } | {
14
+ authorization: string;
15
+ dpop?: string;
16
+ cookie?: never;
17
+ };
18
+ /** The request the app received, as the end user sent it. */
19
+ export type CheckRequestInfo = G['CheckRequest']['request'];
20
+ /** A need in its wire form. */
21
+ export type WireNeed = G['Need'];
22
+ /** One exact operation an agent asks its human to approve. */
23
+ export type Action = G['Action'];
24
+ /** The body of `POST /v1/check`. */
25
+ export type CheckRequest = Omit<G['CheckRequest'], 'credential'> & {
26
+ credential: Credential;
27
+ };
28
+ /** The authenticated caller of a request. */
29
+ export type Principal = Omit<G['Principal'], 'assurance'> & {
30
+ assurance: Assurance;
31
+ };
32
+ /** The answer of `POST /v1/check`: the end user's outcome, with the cookies and headers to send them. */
33
+ export type CheckResult = {
34
+ allowed: true;
35
+ principal: Principal;
36
+ set_cookies: string[];
37
+ headers: Record<string, string>;
38
+ } | {
39
+ allowed: false;
40
+ problem: Problem;
41
+ set_cookies: string[];
42
+ headers: Record<string, string>;
43
+ };
44
+ /** The server's version, the API versions it serves, and its preset. */
45
+ export type Meta = G['Meta'];
46
+ /** The summary of one user. `email` is `null` when the user has no address. */
47
+ export type User = G['User'];
48
+ /** An agent a person owns, as `POST /v1/agents` returns it. */
49
+ export type Agent = G['Agent'];
50
+ /** The answer of `POST /v1/agents/{id}/delegate`: the agent's token, `tsa_…`, shown once. */
51
+ export type Delegated = G['Delegated'];
52
+ /** The answer of `POST /v1/approvals`. */
53
+ export type ApprovalCreated = G['ApprovalCreated'];
54
+ /** One live session, with the sessions delegated from it in `children`. */
55
+ export type Session = Omit<G['Session'], 'kind' | 'children'> & {
56
+ kind: Principal['kind'];
57
+ children: Session[];
58
+ };
59
+ /** The answer of `GET /v1/sessions/tree`. */
60
+ export type SessionTree = {
61
+ sessions: Session[];
62
+ };
63
+ export {};
package/dist/api.js ADDED
@@ -0,0 +1,8 @@
1
+ // The SDK's types of the server's app API (/v1/).
2
+ //
3
+ // gen/api.ts is generated from server/openapi.json with `npm run gen`.
4
+ // Its types are looser than what the server sends: `assurance` is any
5
+ // string. This file narrows them for the SDK's callers, and
6
+ // test/contract.ts fails when a type here names a field the document
7
+ // doesn't have.
8
+ export {};
package/dist/body.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /** The largest body the SDK reads into memory: 1 MiB. */
2
+ export declare const maxBody: number;
3
+ /** A body larger than the limit. The reader was cancelled when the total passed it. */
4
+ export declare class BodyTooLargeError extends RangeError {
5
+ constructor(limit: number);
6
+ }
7
+ /**
8
+ * Reads a request's or response's body into bytes, at most `limit` of
9
+ * them. A `Content-Length` over the limit is refused before any byte is
10
+ * read; otherwise the stream is read chunk by chunk and its reader is
11
+ * cancelled as soon as the total passes the limit. Bytes are counted, not
12
+ * characters.
13
+ */
14
+ export declare function readBytes(msg: Request | Response, limit?: number): Promise<Uint8Array<ArrayBuffer>>;
15
+ /** Reads a body as UTF-8 text, at most `limit` bytes. */
16
+ export declare function readText(msg: Request | Response, limit?: number): Promise<string>;
17
+ /** Reads a body as JSON, at most `limit` bytes. */
18
+ export declare function readJSON<T>(msg: Request | Response, limit?: number): Promise<T>;
package/dist/body.js ADDED
@@ -0,0 +1,55 @@
1
+ // Bounded body reads: no body the SDK reads is buffered past a limit.
2
+ /** The largest body the SDK reads into memory: 1 MiB. */
3
+ export const maxBody = 1 << 20;
4
+ /** A body larger than the limit. The reader was cancelled when the total passed it. */
5
+ export class BodyTooLargeError extends RangeError {
6
+ constructor(limit) {
7
+ super(`body is larger than ${limit} bytes`);
8
+ this.name = 'BodyTooLargeError';
9
+ }
10
+ }
11
+ /**
12
+ * Reads a request's or response's body into bytes, at most `limit` of
13
+ * them. A `Content-Length` over the limit is refused before any byte is
14
+ * read; otherwise the stream is read chunk by chunk and its reader is
15
+ * cancelled as soon as the total passes the limit. Bytes are counted, not
16
+ * characters.
17
+ */
18
+ export async function readBytes(msg, limit = maxBody) {
19
+ const declared = msg.headers.get('content-length');
20
+ if (declared !== null && Number(declared) > limit) {
21
+ await msg.body?.cancel().catch(() => { });
22
+ throw new BodyTooLargeError(limit);
23
+ }
24
+ if (!msg.body)
25
+ return new Uint8Array(0);
26
+ const reader = msg.body.getReader();
27
+ const chunks = [];
28
+ let total = 0;
29
+ for (;;) {
30
+ const { done, value } = await reader.read();
31
+ if (done)
32
+ break;
33
+ total += value.byteLength;
34
+ if (total > limit) {
35
+ await reader.cancel(new BodyTooLargeError(limit)).catch(() => { });
36
+ throw new BodyTooLargeError(limit);
37
+ }
38
+ chunks.push(value);
39
+ }
40
+ const out = new Uint8Array(total);
41
+ let at = 0;
42
+ for (const c of chunks) {
43
+ out.set(c, at);
44
+ at += c.byteLength;
45
+ }
46
+ return out;
47
+ }
48
+ /** Reads a body as UTF-8 text, at most `limit` bytes. */
49
+ export async function readText(msg, limit = maxBody) {
50
+ return new TextDecoder().decode(await readBytes(msg, limit));
51
+ }
52
+ /** Reads a body as JSON, at most `limit` bytes. */
53
+ export async function readJSON(msg, limit = maxBody) {
54
+ return JSON.parse(await readText(msg, limit));
55
+ }