@finalai/sign-in 0.0.0-stage → 0.1.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/HOSTING.md +377 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +74 -2
- package/dist/modules/index.d.mts +124 -0
- package/dist/modules/index.mjs +198 -0
- package/dist/modules/index.mjs.map +7 -0
- package/package.json +39 -4
package/HOSTING.md
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
# Hosting agents: requirements, provide documents and local hosts
|
|
2
|
+
|
|
3
|
+
An agent is a document (data) that states what it requires: a harness within a
|
|
4
|
+
permission ceiling, compute by capability, and named integration slots. Whoever
|
|
5
|
+
starts work provides implementations in a plain `provide` object. This guide is
|
|
6
|
+
for hosts that implement the agent platform API these packages call: what the
|
|
7
|
+
SDK sends, what it expects back, and the connection a client dials to lend its
|
|
8
|
+
own process to an agent.
|
|
9
|
+
|
|
10
|
+
## Selecting a deployment
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
export FINAL_API_HOST=https://<agents-api-host>
|
|
14
|
+
export FINAL_API_KEY=<api-key>
|
|
15
|
+
export FINAL_PROJECT_ID=<project-id>
|
|
16
|
+
pnpm exec final-agents print ./agent.ts # the document, as JSON; calls nothing
|
|
17
|
+
pnpm exec final-agents publish ./agent.ts --name release-scout
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`--host` overrides `FINAL_API_HOST`; `--project` overrides `FINAL_PROJECT_ID`.
|
|
21
|
+
`createClient({ host })` selects a deployment the same way. Nothing in an agent
|
|
22
|
+
names a deployment, a server URL or a credential, so the same document runs
|
|
23
|
+
against any host.
|
|
24
|
+
|
|
25
|
+
## Agents are documents
|
|
26
|
+
|
|
27
|
+
An agent value (`defineAgent`) becomes its document with `documentOf(agent)`:
|
|
28
|
+
identity, instructions, skills, `require`, workspace seed files, each tool's
|
|
29
|
+
name and schema, hooks, tool policy, secret names and schedules. The agent's
|
|
30
|
+
identity is the content hash of the canonical document with defaults applied
|
|
31
|
+
(`agentDocumentHash` from `@finalai/agent-provider/document`, `sha256:<hex>`).
|
|
32
|
+
Hosts must hash with that function; any other canonicalization yields other
|
|
33
|
+
hashes.
|
|
34
|
+
|
|
35
|
+
Each tool and hook says where it runs:
|
|
36
|
+
|
|
37
|
+
- **Serverless** code carries one self-contained ES module (`source`, `export`).
|
|
38
|
+
It runs on the host's serverless runtime from the document alone, whether or
|
|
39
|
+
not any client is connected. Hosts re-check that the source imports nothing.
|
|
40
|
+
- **In-process** code carries only its interface. Its body never leaves the
|
|
41
|
+
process that created the session; the host calls it over that process's
|
|
42
|
+
local host connection (below). With no such connection the tool reports
|
|
43
|
+
itself unavailable and the session carries on.
|
|
44
|
+
|
|
45
|
+
`@finalai/agent-provider/code-host` routes each call by placement
|
|
46
|
+
(`createCodeHost`); the serverless runtime contract is `ServerlessRuntimeIface`.
|
|
47
|
+
A serverless tool gives the model a projection apart from its structured output
|
|
48
|
+
by returning `{ [Symbol.for(SERVERLESS_TOOL_RESULT)]: true, output, modelOutput }`;
|
|
49
|
+
the runtime reads every tool return with `serverlessToolResultOf` and sends
|
|
50
|
+
`modelOutput` on the result line. The model sees `modelOutput` when present,
|
|
51
|
+
and `output` stays the structured result.
|
|
52
|
+
|
|
53
|
+
Routes, under `/api/v1/projects/:projectId/agents`:
|
|
54
|
+
|
|
55
|
+
| Route | Body / query | Response |
|
|
56
|
+
| ---------------- | ----------------------------------- | -------------------------------------- |
|
|
57
|
+
| `PUT /documents` | `{ document \| source, hash? }` | `{ hash }`; refuse a hash that differs |
|
|
58
|
+
| `POST /publish` | `{ name, hash }` | `{ id, name, hash, publishedAt }` |
|
|
59
|
+
| `GET /lookup` | exactly one of `name`, `id`, `hash` | `agentInfoSchema` |
|
|
60
|
+
| `GET /history` | `name`, `cursor?`, `limit?` | `agentHistorySchema` |
|
|
61
|
+
|
|
62
|
+
An agent is always passed as an object, `{ hash, document? }`, never a name. A
|
|
63
|
+
request whose document is absent names a hash the host already stores.
|
|
64
|
+
|
|
65
|
+
A store sends either the document or its `source` (`agentSourceSchema`): the
|
|
66
|
+
files the document is made from, by path. A host given `source` makes the
|
|
67
|
+
document from those files itself and keeps them with it. It refuses a source
|
|
68
|
+
that does not make a document (`agent_source_invalid`, with
|
|
69
|
+
`details.diagnostics`) and, when `hash` is sent, one whose document hashes
|
|
70
|
+
differently (`hash_mismatch`). `GET /lookup` returns the kept files as `source`
|
|
71
|
+
(null when there are none).
|
|
72
|
+
|
|
73
|
+
Every publication keeps its source: `POST /publish` refuses a hash stored without one. A host
|
|
74
|
+
that keeps drafts makes a publication made elsewhere the next draft, and refuses one that lacks
|
|
75
|
+
what was published from drafts since its publisher last published (`draft_conflict`), keeping
|
|
76
|
+
the merge as the newest draft.
|
|
77
|
+
|
|
78
|
+
## Provide documents
|
|
79
|
+
|
|
80
|
+
```json
|
|
81
|
+
{
|
|
82
|
+
"harness": {
|
|
83
|
+
"harness": "pi",
|
|
84
|
+
"configuration": {
|
|
85
|
+
"model": "gpt-6.1-sol",
|
|
86
|
+
"inference": [{ "source": "final", "billTo": "project" }]
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"compute": { "files": "asbx_01J…", "shell": "asbx_01J…" },
|
|
90
|
+
"integrations": { "issues": "intg_01H…" }
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`provideDocumentSchema` (`@finalai/agent-protocol/agent-platform`) is the one
|
|
95
|
+
shape on every call that can start work: `sessions.create`, `conversations.create`
|
|
96
|
+
(per participant, plus a shared document for the conversation), direct and Home
|
|
97
|
+
conversations, `addParticipant`, `PUT …/participants/:pid/provide`, channel
|
|
98
|
+
installs (`agents.provide`) and schedules. It names only things that exist: a
|
|
99
|
+
sandbox or integration by id, harness settings inline. Hosts store it as given
|
|
100
|
+
and resolve participant, then conversation, then the install or schedule that
|
|
101
|
+
created the conversation, taking each top-level key whole from the nearest scope
|
|
102
|
+
that sets it. A conversation returns its shared document as `provide`, so a
|
|
103
|
+
client can run the same check before adding a participant. Nothing has a
|
|
104
|
+
default on the host.
|
|
105
|
+
|
|
106
|
+
`files` and `shell` must name the same sandbox. A sandbox or integration id
|
|
107
|
+
must belong to the session's project.
|
|
108
|
+
|
|
109
|
+
## The requirements check
|
|
110
|
+
|
|
111
|
+
Every call that can start work runs `unmetRequirements` from
|
|
112
|
+
`@finalai/agent-provider/requirements-check` with what the host knows (each
|
|
113
|
+
sandbox's capabilities, which integrations exist, the composed harness via
|
|
114
|
+
`harnessCheckInputOf`, whether a client holding the in-process code is
|
|
115
|
+
connected). If anything is unmet, nothing is created and the response is:
|
|
116
|
+
|
|
117
|
+
```json
|
|
118
|
+
{
|
|
119
|
+
"error": {
|
|
120
|
+
"code": "requirements_unmet",
|
|
121
|
+
"message": "…",
|
|
122
|
+
"details": {
|
|
123
|
+
"agent": "sha256:…",
|
|
124
|
+
"requirements": [
|
|
125
|
+
{
|
|
126
|
+
"kind": "integration",
|
|
127
|
+
"name": "issues",
|
|
128
|
+
"description": "Issue tracker",
|
|
129
|
+
"problem": "not_provided",
|
|
130
|
+
"detail": null
|
|
131
|
+
}
|
|
132
|
+
]
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`harness_unsuitable` has the same body for a harness change refused on its own.
|
|
139
|
+
The SDK runs the same function before sending, so a caller sees the same list
|
|
140
|
+
either way; the SDK error carries `code` and `requirements`
|
|
141
|
+
(`isRequirementsUnmetError`).
|
|
142
|
+
|
|
143
|
+
A running agent therefore always has what it requires: the host adds nothing to
|
|
144
|
+
its context about requirements. An optional requirement that was not provided is
|
|
145
|
+
simply absent.
|
|
146
|
+
|
|
147
|
+
## Harnesses, ACP adapters and environments
|
|
148
|
+
|
|
149
|
+
Three independent pieces reach a model loop, and the host speaks only ACP v2:
|
|
150
|
+
|
|
151
|
+
- a **harness** definition: the agent program (it need not speak ACP);
|
|
152
|
+
- an **ACP adapter** definition: maps one harness interface to ACP v2, reusable
|
|
153
|
+
across harnesses; a harness that speaks ACP v2 needs none;
|
|
154
|
+
- an **environment**: a sandbox that runs them, or an ACP v2 endpoint already
|
|
155
|
+
running at a URL.
|
|
156
|
+
|
|
157
|
+
Harness settings name them:
|
|
158
|
+
`{ harness, adapter?, configuration, environment? }`. `adapter` defaults to the
|
|
159
|
+
harness definition's. `environment` is a sandbox id (the pair is started
|
|
160
|
+
there), `{ url, hop? }` (nothing is started), or absent: a harness that uses
|
|
161
|
+
`files` or `shell` natively then runs in the sandbox provided for `shell`; any
|
|
162
|
+
other harness is refused.
|
|
163
|
+
|
|
164
|
+
Definitions are data (`harnessDefinitionSchema`, `acpAdapterDefinitionSchema`
|
|
165
|
+
in `@finalai/agent-provider/harness-definition`), published by name and stored
|
|
166
|
+
by content hash. A harness definition carries its configuration's JSON Schema,
|
|
167
|
+
supported features, `lowestPermission`, accepted inference sources, what it uses
|
|
168
|
+
natively from where it runs (`native.files`, `native.shell`), its interface and
|
|
169
|
+
default adapter, ACP behaviour (`promptWhileRunning`, `sessionSurvivesDisconnect`,
|
|
170
|
+
`supports`, `mcp`, `consumes`), and `run` entries per runtime kind:
|
|
171
|
+
|
|
172
|
+
- `process`: a command, with arguments and environment derived from the
|
|
173
|
+
configuration by templates (`{{configuration.model}}`, groups included
|
|
174
|
+
`when` a value is set). An adapter's process entry wraps the harness's
|
|
175
|
+
(`{{harness.command}}`, `{ spread: 'harness.args' }`).
|
|
176
|
+
- `worker`: a program built for a worker runtime, by name.
|
|
177
|
+
|
|
178
|
+
An environment runs what its sandbox provider declares
|
|
179
|
+
(`SandboxEnvironmentImplementationIface.runtimes`: `process`, `worker`; absent
|
|
180
|
+
means `process` when it offers `shell`). A worker runtime is not a machine: it
|
|
181
|
+
offers the model no files or shell, so a harness running there reaches the
|
|
182
|
+
sandboxes provided for them over the handle RPC. `composeHarness` picks a
|
|
183
|
+
runtime kind the environment, the harness and the adapter all have, and
|
|
184
|
+
`harnessCheckInputOf` turns the result into the requirements check's input: a
|
|
185
|
+
harness's native capabilities are its environment's, so only that sandbox may
|
|
186
|
+
be provided for them. `harnessStartFor` renders what to start.
|
|
187
|
+
|
|
188
|
+
A harness provider (`HarnessProviderIface`, `@finalai/agent-provider/harness-provider`)
|
|
189
|
+
reaches a harness: `open` and `resume` return an ACP endpoint (`ws`, `http`, or
|
|
190
|
+
`sandbox`: a process or worker program the session service starts in the
|
|
191
|
+
environment sandbox over the handle RPC, ACP on its stdio or stream, with no
|
|
192
|
+
port exposed), and `park`, `close` and `health` follow its lifecycle. The
|
|
193
|
+
general provider starts adapter(harness) from the definitions; a definition
|
|
194
|
+
whose harness is reached some other way carries its own provider code
|
|
195
|
+
(`defineHarnessProvider`), one self-contained module run on the serverless
|
|
196
|
+
runtime.
|
|
197
|
+
|
|
198
|
+
Routes, under `/api/v1/projects/:projectId`:
|
|
199
|
+
|
|
200
|
+
| Route | Body or query | Response |
|
|
201
|
+
| ------------------------------------------ | ------------------------------------ | --------------------------------- |
|
|
202
|
+
| `POST /harnesses/check` | `{ agent: hash, harness, compute? }` | `harnessCheckResponseSchema` |
|
|
203
|
+
| `POST /harnesses/publish` | `{ name, definition, hash? }` | `definitionPublicationSchema` |
|
|
204
|
+
| `GET /harnesses/lookup` | `name` or `hash` | `harnessDefinitionInfoSchema` |
|
|
205
|
+
| `GET /harnesses` | | `harnessDefinitionListSchema` |
|
|
206
|
+
| `POST /acp-adapters/publish` | `{ name, definition, hash? }` | `definitionPublicationSchema` |
|
|
207
|
+
| `GET /acp-adapters/lookup` | `name` or `hash` | `acpAdapterDefinitionInfoSchema` |
|
|
208
|
+
| `GET /acp-adapters` | | `acpAdapterDefinitionListSchema` |
|
|
209
|
+
| `GET /subscription-allowances` | | `subscriptionAllowanceListSchema` |
|
|
210
|
+
| `PUT /subscription-allowances/:harness` | `{}` | `subscriptionAllowanceSchema` |
|
|
211
|
+
| `DELETE /subscription-allowances/:harness` | | `{ ok }` |
|
|
212
|
+
|
|
213
|
+
The check answers `{ suitable, problems, compute, environment, adapter,
|
|
214
|
+
runtime }`, where `compute[capability].status` is `harness` (its environment
|
|
215
|
+
serves it natively), `sandbox` (a provided sandbox must) or `unavailable`. A
|
|
216
|
+
project can name its own definitions, its ancestors' and the public catalog's.
|
|
217
|
+
A subscription inference source reaches a harness only when the project allows
|
|
218
|
+
that harness, or the public catalog does for its own definitions. The model is
|
|
219
|
+
a string the harness validates; the host never substitutes a default model.
|
|
220
|
+
|
|
221
|
+
## Sandboxes and setups
|
|
222
|
+
|
|
223
|
+
Under `/api/v1/projects/:projectId`: `POST /sandboxes` (`{ provider, environment,
|
|
224
|
+
setup?, ownedBy?, idempotencyKey? }`; creating boots nothing), `GET` and
|
|
225
|
+
`DELETE /sandboxes/:id`, `GET /sandboxes/:id/description`, and
|
|
226
|
+
`POST /sandboxes/:id/run` (`{ command, cwd?, env?, timeoutMs? }` →
|
|
227
|
+
`{ exitCode, stdout, stderr }`, booting the sandbox if needed). A sandbox owned
|
|
228
|
+
by a conversation or session is deleted with its owner. A retried create with
|
|
229
|
+
the same `idempotencyKey` returns the first sandbox. Sandbox setups are
|
|
230
|
+
published with `POST /sandbox-setups` (`{ name, setup }`); `latest` resolves once,
|
|
231
|
+
when a sandbox is created.
|
|
232
|
+
|
|
233
|
+
## Integrations and sign-in
|
|
234
|
+
|
|
235
|
+
Integrations are project resources: an MCP server and how calls to it
|
|
236
|
+
authenticate (`oauth` personal or shared, `secret` by project secret name,
|
|
237
|
+
`platform-identity`, `none`). A person's own sign-in is runtime state: on the
|
|
238
|
+
first call that needs it, the host raises a `sign_in` decision for that person,
|
|
239
|
+
holds the call, and continues it when `POST /api/v1/sign-ins/complete` succeeds.
|
|
240
|
+
`platform-identity` sends a short-lived signed assertion of the calling session
|
|
241
|
+
that any server can verify against the host's published keys; Final's gateway is
|
|
242
|
+
an ordinary integration with this auth.
|
|
243
|
+
|
|
244
|
+
### Integration tool policy
|
|
245
|
+
|
|
246
|
+
A slot's `tools` (`allow`, `deny`, `load`, `allowAnnotations`,
|
|
247
|
+
`denyAnnotations`) and `approvals` are a ceiling over whatever integration fills
|
|
248
|
+
it. Keys are tool names or `*` patterns: `*` matches any run of characters,
|
|
249
|
+
`deny` wins over `allow`, and the most specific key governs (an exact name, else
|
|
250
|
+
the pattern with the most literal characters, ties toward `ask`). Hosts enforce
|
|
251
|
+
this with `isToolExposed`, `isToolLoaded`, `toolApprovalOf` and
|
|
252
|
+
`resolveToolApprovalKey` from `@finalai/agent-provider`.
|
|
253
|
+
|
|
254
|
+
An annotation selector matches when every hint it sets equals the tool's hint,
|
|
255
|
+
reading omitted hints as the MCP spec's defaults (not read-only, destructive, not
|
|
256
|
+
idempotent, open world). Annotations come from the integration's server, so
|
|
257
|
+
select on them only for servers trusted to classify their own tools.
|
|
258
|
+
|
|
259
|
+
With `load`, the host lists only the loaded tools and keeps every other exposed
|
|
260
|
+
tool reachable through a search over the integration's remaining tools and a
|
|
261
|
+
call that runs a found tool by its real name, with the same exposure and
|
|
262
|
+
approval checks as a direct call. Without `load`, the host lists every exposed
|
|
263
|
+
tool except tools a server labels with a connector in `_meta`
|
|
264
|
+
(`{ "ai.final/connector": { "namespace": "…", "name": "…" } }`) and tools past
|
|
265
|
+
the host's listing limit, which it searches instead. A harness that declares
|
|
266
|
+
`supports.deferredToolSearch` searches tools itself, so the host lists every
|
|
267
|
+
exposed tool to it.
|
|
268
|
+
|
|
269
|
+
## Local hosts
|
|
270
|
+
|
|
271
|
+
A client that starts an agent can lend its own process to it: it serves the
|
|
272
|
+
agent's `files` and `shell` (any it was not given a sandbox for, unless created
|
|
273
|
+
with `localCompute: false`) and answers calls to the agent's in-process tools,
|
|
274
|
+
hooks and approval predicates. It does so over one WebSocket per agent it
|
|
275
|
+
started:
|
|
276
|
+
|
|
277
|
+
```
|
|
278
|
+
GET /api/v1/projects/:projectId/local-hosts (WebSocket upgrade)
|
|
279
|
+
Sec-WebSocket-Protocol: final.local-host.v1
|
|
280
|
+
Authorization: Bearer <the client's credential>
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
The socket carries two protocols. Binary frames are always the sandbox handle
|
|
284
|
+
RPC's stream chunks. A text frame belongs to the **host protocol** when it is a
|
|
285
|
+
JSON-RPC request or notification whose method starts with `host/` or `code/`, or
|
|
286
|
+
a response (or `$/cancel_request`) whose id is a string starting with `host:`.
|
|
287
|
+
Every other text frame is the **sandbox handle RPC**
|
|
288
|
+
(`@finalai/agent-provider/sandbox/wire`), in which the host is the RPC client and
|
|
289
|
+
the client process serves the sandbox: the host sends `initialize`,
|
|
290
|
+
`sandbox/readFile`, `sandbox/run` and the rest, with numeric ids, gated by a grant
|
|
291
|
+
of the access the agent requires on the capabilities it serves.
|
|
292
|
+
`splitLocalHostChannel` and `createHostPeer` from `@finalai/agents/client/local-host`
|
|
293
|
+
implement both sides of the split.
|
|
294
|
+
|
|
295
|
+
**`host/hello`** (client → host, first): the client's id is `host:1`.
|
|
296
|
+
|
|
297
|
+
```json
|
|
298
|
+
{
|
|
299
|
+
"jsonrpc": "2.0",
|
|
300
|
+
"id": "host:1",
|
|
301
|
+
"method": "host/hello",
|
|
302
|
+
"params": {
|
|
303
|
+
"protocolVersion": 1,
|
|
304
|
+
"owner": { "kind": "session", "id": "ases_…" },
|
|
305
|
+
"agent": "sha256:…",
|
|
306
|
+
"capabilities": ["files", "shell"],
|
|
307
|
+
"tools": ["find_order"],
|
|
308
|
+
"hooks": [],
|
|
309
|
+
"approvals": [],
|
|
310
|
+
"resume": "lhost_…"
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
`owner.kind` is `session` or `conversation`; `owner.id` is absent when the
|
|
316
|
+
caller chose no id, and the host reserves one the client then creates with.
|
|
317
|
+
`resume` is a host id from an earlier connection. The result:
|
|
318
|
+
|
|
319
|
+
```json
|
|
320
|
+
{
|
|
321
|
+
"jsonrpc": "2.0",
|
|
322
|
+
"id": "host:1",
|
|
323
|
+
"result": {
|
|
324
|
+
"hostId": "lhost_…",
|
|
325
|
+
"owner": { "kind": "session", "id": "ases_…" },
|
|
326
|
+
"sandboxId": "asbx_…"
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
`sandboxId` names this connection's compute in `provide.compute` (one sandbox for
|
|
332
|
+
both capabilities, as the requirements check demands); it is null when the
|
|
333
|
+
client serves no capability. The sandbox belongs to the owner and is deleted
|
|
334
|
+
with it.
|
|
335
|
+
|
|
336
|
+
**`code/run`** (host → client): params are one code invocation
|
|
337
|
+
(`codeInvocationSchema` from `@finalai/agent-provider/code-host`: `kind` tool,
|
|
338
|
+
hook or approval, the `name` in the document, `input` or `event` and `payload`,
|
|
339
|
+
and a `context` with `sessionId`, `callId`, `actingUserId` and the session's
|
|
340
|
+
compute endpoints for `ctx.sandbox(capability)`). A hook's payload is
|
|
341
|
+
`{ data, meta: { id, at, seq } }`. The result is the final line:
|
|
342
|
+
`{ "type": "result", "output": …, "modelOutput"?: … }` or
|
|
343
|
+
`{ "type": "error", "message": "…" }`; an approval answers `output: true` to
|
|
344
|
+
ask first. While it runs the client sends **`code/progress`** notifications
|
|
345
|
+
`{ "requestId": "host:7", "data": …, "label"?: "…" }`. The host cancels with
|
|
346
|
+
`$/cancel_request { "requestId": "host:7" }`.
|
|
347
|
+
|
|
348
|
+
**`code/secret`** (client → host): in-process code reading `ctx.secrets.get(name)`
|
|
349
|
+
asks with `{ "requestId": "host:7", "name": "BILLING_TOKEN" }`, where
|
|
350
|
+
`requestId` is the `code/run` it runs for. The host answers
|
|
351
|
+
`{ "value": "…" | null }` (null when the secret is not set). It refuses a name
|
|
352
|
+
the agent's document does not list in `secrets`, a `requestId` that is not a
|
|
353
|
+
`code/run` in flight on this connection, and resolves the name in the project
|
|
354
|
+
of the session or conversation the host serves. The client refuses unlisted
|
|
355
|
+
names itself before asking.
|
|
356
|
+
|
|
357
|
+
When the socket closes the session carries on. Until a connection resumes it,
|
|
358
|
+
the host reports this process's in-process tools as unavailable
|
|
359
|
+
(`CodeErrorCode.Unavailable`) and its sandbox as unreachable. The SDK's socket
|
|
360
|
+
does not keep a Node process alive, so a script that is done exits and its tools
|
|
361
|
+
become unavailable.
|
|
362
|
+
|
|
363
|
+
## Host integration
|
|
364
|
+
|
|
365
|
+
These packages define contracts and client behaviour, not a platform. A host
|
|
366
|
+
implementing them must:
|
|
367
|
+
|
|
368
|
+
1. Store documents by `agentDocumentHash`, re-check self-contained serverless
|
|
369
|
+
source, make documents from agent `source` without giving that code network
|
|
370
|
+
or host access, and point names at hashes only when someone publishes.
|
|
371
|
+
2. Run `unmetRequirements` on every call that starts work and at every session
|
|
372
|
+
open, and create nothing when it fails.
|
|
373
|
+
3. Store each `provide` as given; never fill a requirement on a caller's behalf.
|
|
374
|
+
4. Route each tool and hook by its placement: serverless code to its runtime with
|
|
375
|
+
the source from the document, in-process code to the local host that holds it.
|
|
376
|
+
5. Resolve integration auth per call for the acting person, raising sign-in as
|
|
377
|
+
that integration's auth step.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @finalai/sign-in
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sign in with Final: the OpenID Connect authorization code flow with S256 PKCE against Final's
|
|
4
|
+
authorization server, built on [oauth4webapi](https://github.com/panva/oauth4webapi). It also
|
|
5
|
+
re-exports `verifyIdToken` and `getVisitor` from `@finalai/agent-protocol/identity`, so an app
|
|
6
|
+
needs one import. WebCrypto, `fetch` and URL only: it runs in Node, Cloudflare Workers, Deno
|
|
7
|
+
and browsers.
|
|
8
|
+
|
|
9
|
+
The protocol is oauth4webapi's; this package adds only Final's defaults: Final's endpoints
|
|
10
|
+
(until Final publishes discovery), `openid` in every scope, a required `iss` on every
|
|
11
|
+
authorization response (RFC 9207), EdDSA ID tokens verified against Final's JWKS, a
|
|
12
|
+
`private_key_jwt` client assertion from a private JWK, `resource` (RFC 8707), and typed
|
|
13
|
+
results instead of exceptions. Names follow `openid-client`.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createSignInClient } from '@finalai/sign-in';
|
|
17
|
+
|
|
18
|
+
const client = await createSignInClient({
|
|
19
|
+
issuer: 'https://auth.control.final.ai',
|
|
20
|
+
clientId: 'https://app.example',
|
|
21
|
+
redirectUri: 'https://app.example/callback',
|
|
22
|
+
// The private half of the registered JWK (Ed25519, P-256 or RSA); omit for a public client.
|
|
23
|
+
clientPrivateJwk,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Sign-in: keep `checks` with the browser (an HttpOnly cookie, say), then redirect to `url`.
|
|
27
|
+
const { url, checks } = await client.createAuthorizationRequest({
|
|
28
|
+
scope: 'profile',
|
|
29
|
+
resource: 'https://app.example',
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Callback: the request's URL (relative is fine), or the body of a form_post.
|
|
33
|
+
const result = await client.authorizationCodeGrant(request.url, checks);
|
|
34
|
+
if (result.ok) result.claims.subject; // the person's Final user ID
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
- `createSignInClient({ issuer, clientId, redirectUri, endpoints?, clientPrivateJwk?, fetch?, jwks? })`
|
|
38
|
+
imports the key and rejects only when it is not a usable private key. `endpoints` defaults to
|
|
39
|
+
`finalSignInEndpoints(issuer)`: `/oauth/authorize`, `/oauth/token` and
|
|
40
|
+
`/.well-known/jwks.json` under the issuer.
|
|
41
|
+
- `createAuthorizationRequest({ scope, resource?, responseMode?, prompt?, loginHint?, maxAge?, organizationId?, extraParams? })`
|
|
42
|
+
returns `{ url, checks }`. `checks` (`expectedState`, `expectedNonce`, `pkceCodeVerifier`, and
|
|
43
|
+
`maxAge` and `expectedOrganizationId` when asked for) is exactly what `authorizationCodeGrant`
|
|
44
|
+
takes, and plain JSON to store.
|
|
45
|
+
- `prompt` is `none`, `login` or `consent`; `organizationId` is sent as `organization`.
|
|
46
|
+
- `extraParams` adds parameters but never replaces one the client sets.
|
|
47
|
+
- `buildAuthorizationUrl({ ...the same, state, nonce, codeVerifier })` is for callers that make
|
|
48
|
+
their own values with `randomState()`, `randomNonce()` and `randomPKCECodeVerifier()`.
|
|
49
|
+
- `authorizationCodeGrant(callback, checks)` validates the callback, redeems the code, verifies
|
|
50
|
+
the ID token, and checks its `auth_time` against `maxAge` and its `org` against
|
|
51
|
+
`expectedOrganizationId`. It never throws.
|
|
52
|
+
- Success is `{ ok: true, claims, idToken, accessToken, expiresAt, refreshToken, scope }`.
|
|
53
|
+
`expiresAt` is in milliseconds since the epoch, like the claims' times. `refreshToken` is
|
|
54
|
+
null: Final issues none yet.
|
|
55
|
+
- Failure is `{ ok: false, failure }`. `SignInFailure` is closed, so a new value is a breaking
|
|
56
|
+
change; an OAuth error code without its own value arrives as `authorization_error` or
|
|
57
|
+
`token_error` with the code in `error`:
|
|
58
|
+
- `invalid_callback`, `issuer_mismatch`, `state_mismatch`;
|
|
59
|
+
- `access_denied`, `login_required` (also for `interaction_required`, `consent_required`
|
|
60
|
+
and `account_selection_required`, as after `prompt=none`), `authorization_error`, and
|
|
61
|
+
`token_error`, each with `error` and `errorDescription`;
|
|
62
|
+
- `token_endpoint_unavailable`, `invalid_response`;
|
|
63
|
+
- `invalid_id_token` (with `refusal`), `max_age_exceeded`, `organization_mismatch`.
|
|
64
|
+
- `verifyIdToken` and `getVisitor` are documented in
|
|
65
|
+
[`@finalai/agent-protocol`](../agent-protocol/README.md). A resource server, such as a Final
|
|
66
|
+
Cloud function, calls `getVisitor(request, { issuer })` on every request to learn who it
|
|
67
|
+
serves, and whether an agent acts for them (`actor`).
|
|
68
|
+
|
|
69
|
+
Final's authorization endpoint does not act on `prompt`, `max_age`, `login_hint` or
|
|
70
|
+
`organization` yet; the client sends them, and its `maxAge` and organization checks hold
|
|
71
|
+
regardless.
|
|
72
|
+
|
|
73
|
+
`accessToken` is for the sign-in's `resource` when it names one. Once Final publishes OpenID
|
|
74
|
+
Connect discovery, any standard client (`openid-client`, Auth.js, Better Auth) works with just
|
|
75
|
+
the issuer.
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { TokenRefusal, type IdTokenIface, type JwksIface, type JwksKeySourceIface } from '@finalai/agent-protocol/identity';
|
|
2
|
+
import * as oauth from 'oauth4webapi';
|
|
3
|
+
export { getVisitor, TokenRefusal, verifyIdToken, type GetVisitorOptionsIface, type IdTokenIface, type VisitorActorIface, type VisitorIface, } from '@finalai/agent-protocol/identity';
|
|
4
|
+
export declare const randomState: typeof oauth.generateRandomState;
|
|
5
|
+
export declare const randomNonce: typeof oauth.generateRandomNonce;
|
|
6
|
+
export declare const randomPKCECodeVerifier: typeof oauth.generateRandomCodeVerifier;
|
|
7
|
+
export interface SignInEndpointsIface {
|
|
8
|
+
authorizationEndpoint: string;
|
|
9
|
+
tokenEndpoint: string;
|
|
10
|
+
jwksUri: string;
|
|
11
|
+
}
|
|
12
|
+
/** Final's endpoints under an issuer, until it publishes OpenID Connect discovery. */
|
|
13
|
+
export declare const finalSignInEndpoints: (issuer: string) => SignInEndpointsIface;
|
|
14
|
+
export interface SignInClientOptionsIface {
|
|
15
|
+
/** The authorization server's origin, e.g. `https://auth.control.final.ai`. */
|
|
16
|
+
issuer: string;
|
|
17
|
+
clientId: string;
|
|
18
|
+
/** Exactly as registered. */
|
|
19
|
+
redirectUri: string;
|
|
20
|
+
/** Defaults to `finalSignInEndpoints(issuer)`. */
|
|
21
|
+
endpoints?: SignInEndpointsIface;
|
|
22
|
+
/**
|
|
23
|
+
* The private JWK registered for private_key_jwt (Ed25519, P-256 or RSA); omit for a public
|
|
24
|
+
* client, which authenticates with PKCE alone.
|
|
25
|
+
*/
|
|
26
|
+
clientPrivateJwk?: JsonWebKey & {
|
|
27
|
+
kid?: string;
|
|
28
|
+
};
|
|
29
|
+
fetch?: typeof fetch;
|
|
30
|
+
/** The issuer's keys; defaults to fetching and caching `endpoints.jwksUri`. */
|
|
31
|
+
jwks?: JwksIface | JwksKeySourceIface;
|
|
32
|
+
}
|
|
33
|
+
/** What a sign-in asks for; `createAuthorizationRequest` takes these alone. */
|
|
34
|
+
export interface AuthorizationRequestArgsIface {
|
|
35
|
+
/** Space-separated; `openid` is added when missing. */
|
|
36
|
+
scope: string;
|
|
37
|
+
/** RFC 8707: the origin to get an access token for (a private site's own origin). */
|
|
38
|
+
resource?: string;
|
|
39
|
+
responseMode?: 'query' | 'form_post';
|
|
40
|
+
/** `none` signs in only without any interaction, else fails with `login_required`. */
|
|
41
|
+
prompt?: 'none' | 'login' | 'consent';
|
|
42
|
+
loginHint?: string;
|
|
43
|
+
/** Seconds since the person last authenticated; the grant checks the ID token's `auth_time`. */
|
|
44
|
+
maxAge?: number;
|
|
45
|
+
/** The organization to sign in under (`organization`); the grant checks the ID token's `org`. */
|
|
46
|
+
organizationId?: string;
|
|
47
|
+
/** Further parameters; they never replace one this sets. */
|
|
48
|
+
extraParams?: Record<string, string>;
|
|
49
|
+
}
|
|
50
|
+
export interface AuthorizationUrlArgsIface extends AuthorizationRequestArgsIface {
|
|
51
|
+
/** From `randomState()`, kept with the browser until the callback, as are the next two. */
|
|
52
|
+
state: string;
|
|
53
|
+
nonce: string;
|
|
54
|
+
/** From `randomPKCECodeVerifier()`; the URL carries its S256 challenge. */
|
|
55
|
+
codeVerifier: string;
|
|
56
|
+
}
|
|
57
|
+
/** What `authorizationCodeGrant` checks: keep it with the browser until the callback. */
|
|
58
|
+
export interface AuthorizationChecksIface {
|
|
59
|
+
expectedState: string;
|
|
60
|
+
expectedNonce: string;
|
|
61
|
+
pkceCodeVerifier: string;
|
|
62
|
+
maxAge?: number;
|
|
63
|
+
expectedOrganizationId?: string;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Why a sign-in failed. Closed: a new value is a breaking change. An OAuth error code with no
|
|
67
|
+
* value of its own arrives as `authorization_error` or `token_error`, with the code in `error`.
|
|
68
|
+
*/
|
|
69
|
+
export declare enum SignInFailure {
|
|
70
|
+
InvalidCallback = "invalid_callback",
|
|
71
|
+
IssuerMismatch = "issuer_mismatch",
|
|
72
|
+
StateMismatch = "state_mismatch",
|
|
73
|
+
AccessDenied = "access_denied",
|
|
74
|
+
LoginRequired = "login_required",
|
|
75
|
+
AuthorizationError = "authorization_error",
|
|
76
|
+
TokenEndpointUnavailable = "token_endpoint_unavailable",
|
|
77
|
+
TokenError = "token_error",
|
|
78
|
+
InvalidIdToken = "invalid_id_token",
|
|
79
|
+
MaxAgeExceeded = "max_age_exceeded",
|
|
80
|
+
OrganizationMismatch = "organization_mismatch",
|
|
81
|
+
InvalidResponse = "invalid_response"
|
|
82
|
+
}
|
|
83
|
+
type OAuthFailure = SignInFailure.AccessDenied | SignInFailure.LoginRequired | SignInFailure.AuthorizationError | SignInFailure.TokenError;
|
|
84
|
+
type PlainFailure = Exclude<SignInFailure, OAuthFailure | SignInFailure.InvalidIdToken>;
|
|
85
|
+
export type SignInResultType = {
|
|
86
|
+
ok: true;
|
|
87
|
+
/** The verified ID token's claims: `subject` is the person's Final user ID. */
|
|
88
|
+
claims: IdTokenIface;
|
|
89
|
+
idToken: string;
|
|
90
|
+
/** For the sign-in's `resource`, or else for userinfo. */
|
|
91
|
+
accessToken: string;
|
|
92
|
+
/** Milliseconds since the epoch, like `IdTokenIface`; null when the response gave none. */
|
|
93
|
+
expiresAt: number | null;
|
|
94
|
+
/** Null: Final issues no refresh tokens yet. */
|
|
95
|
+
refreshToken: string | null;
|
|
96
|
+
scope: string | null;
|
|
97
|
+
} | {
|
|
98
|
+
ok: false;
|
|
99
|
+
failure: OAuthFailure;
|
|
100
|
+
error: string;
|
|
101
|
+
errorDescription: string | null;
|
|
102
|
+
} | {
|
|
103
|
+
ok: false;
|
|
104
|
+
failure: SignInFailure.InvalidIdToken;
|
|
105
|
+
refusal: TokenRefusal;
|
|
106
|
+
} | {
|
|
107
|
+
ok: false;
|
|
108
|
+
failure: PlainFailure;
|
|
109
|
+
};
|
|
110
|
+
export interface SignInClientIface {
|
|
111
|
+
/** A sign-in's URL, with its state, nonce and verifier made and returned as `checks`. */
|
|
112
|
+
createAuthorizationRequest(args: AuthorizationRequestArgsIface): Promise<{
|
|
113
|
+
url: URL;
|
|
114
|
+
checks: AuthorizationChecksIface;
|
|
115
|
+
}>;
|
|
116
|
+
buildAuthorizationUrl(args: AuthorizationUrlArgsIface): Promise<URL>;
|
|
117
|
+
/** The callback: its URL (relative resolves against the redirect URI), or a form_post body. */
|
|
118
|
+
authorizationCodeGrant(callback: string | URL | URLSearchParams, checks: AuthorizationChecksIface): Promise<SignInResultType>;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* A client for one registered redirect URI. It imports `clientPrivateJwk` first, and rejects when
|
|
122
|
+
* that is not a usable private key: a configuration error, unlike every sign-in's outcome.
|
|
123
|
+
*/
|
|
124
|
+
export declare const createSignInClient: (options: SignInClientOptionsIface) => Promise<SignInClientIface>;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import {
|
|
2
|
+
JWKS_PATH,
|
|
3
|
+
remoteJwks,
|
|
4
|
+
TokenRefusal,
|
|
5
|
+
verifyIdToken
|
|
6
|
+
} from "@finalai/agent-protocol/identity";
|
|
7
|
+
import * as oauth from "oauth4webapi";
|
|
8
|
+
import {
|
|
9
|
+
getVisitor,
|
|
10
|
+
TokenRefusal as TokenRefusal2,
|
|
11
|
+
verifyIdToken as verifyIdToken2
|
|
12
|
+
} from "@finalai/agent-protocol/identity";
|
|
13
|
+
const randomState = oauth.generateRandomState;
|
|
14
|
+
const randomNonce = oauth.generateRandomNonce;
|
|
15
|
+
const randomPKCECodeVerifier = oauth.generateRandomCodeVerifier;
|
|
16
|
+
const finalSignInEndpoints = (issuer) => ({
|
|
17
|
+
authorizationEndpoint: `${issuer}/oauth/authorize`,
|
|
18
|
+
tokenEndpoint: `${issuer}/oauth/token`,
|
|
19
|
+
jwksUri: `${issuer}${JWKS_PATH}`
|
|
20
|
+
});
|
|
21
|
+
var SignInFailure = /* @__PURE__ */ ((SignInFailure2) => {
|
|
22
|
+
SignInFailure2["InvalidCallback"] = "invalid_callback";
|
|
23
|
+
SignInFailure2["IssuerMismatch"] = "issuer_mismatch";
|
|
24
|
+
SignInFailure2["StateMismatch"] = "state_mismatch";
|
|
25
|
+
SignInFailure2["AccessDenied"] = "access_denied";
|
|
26
|
+
SignInFailure2["LoginRequired"] = "login_required";
|
|
27
|
+
SignInFailure2["AuthorizationError"] = "authorization_error";
|
|
28
|
+
SignInFailure2["TokenEndpointUnavailable"] = "token_endpoint_unavailable";
|
|
29
|
+
SignInFailure2["TokenError"] = "token_error";
|
|
30
|
+
SignInFailure2["InvalidIdToken"] = "invalid_id_token";
|
|
31
|
+
SignInFailure2["MaxAgeExceeded"] = "max_age_exceeded";
|
|
32
|
+
SignInFailure2["OrganizationMismatch"] = "organization_mismatch";
|
|
33
|
+
SignInFailure2["InvalidResponse"] = "invalid_response";
|
|
34
|
+
return SignInFailure2;
|
|
35
|
+
})(SignInFailure || {});
|
|
36
|
+
const importParams = (jwk) => jwk.kty === "RSA" ? { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } : jwk.kty === "EC" ? { name: "ECDSA", namedCurve: "P-256" } : { name: "Ed25519" };
|
|
37
|
+
const clientAuthOf = async (jwk) => {
|
|
38
|
+
if (jwk == null) return oauth.None();
|
|
39
|
+
const { kid, alg: _alg, key_ops: _ops, use: _use, ...members } = jwk;
|
|
40
|
+
const key = await crypto.subtle.importKey("jwk", members, importParams(jwk), false, ["sign"]);
|
|
41
|
+
return oauth.PrivateKeyJwt(kid == null ? key : { key, kid });
|
|
42
|
+
};
|
|
43
|
+
const LOGIN_REQUIRED = [
|
|
44
|
+
"login_required",
|
|
45
|
+
"interaction_required",
|
|
46
|
+
"consent_required",
|
|
47
|
+
"account_selection_required"
|
|
48
|
+
];
|
|
49
|
+
const failed = (failure) => ({ ok: false, failure });
|
|
50
|
+
const oauthError = (failure, error) => ({
|
|
51
|
+
ok: false,
|
|
52
|
+
failure,
|
|
53
|
+
error: error.error,
|
|
54
|
+
errorDescription: error.error_description ?? null
|
|
55
|
+
});
|
|
56
|
+
const createSignInClient = async (options) => {
|
|
57
|
+
const auth = await clientAuthOf(options.clientPrivateJwk);
|
|
58
|
+
const endpoints = options.endpoints ?? finalSignInEndpoints(options.issuer);
|
|
59
|
+
const server = {
|
|
60
|
+
issuer: options.issuer,
|
|
61
|
+
authorization_endpoint: endpoints.authorizationEndpoint,
|
|
62
|
+
token_endpoint: endpoints.tokenEndpoint,
|
|
63
|
+
jwks_uri: endpoints.jwksUri,
|
|
64
|
+
authorization_response_iss_parameter_supported: true
|
|
65
|
+
};
|
|
66
|
+
const client = {
|
|
67
|
+
client_id: options.clientId,
|
|
68
|
+
id_token_signed_response_alg: "EdDSA"
|
|
69
|
+
};
|
|
70
|
+
const doFetch = options.fetch;
|
|
71
|
+
const http = doFetch == null ? {} : { [oauth.customFetch]: doFetch };
|
|
72
|
+
const keys = options.jwks != null ? { jwks: options.jwks } : doFetch == null ? { jwksUrl: endpoints.jwksUri } : { jwks: remoteJwks({ url: endpoints.jwksUri, fetch: doFetch }) };
|
|
73
|
+
const verify = (token, nonce) => verifyIdToken({ token, issuer: options.issuer, clientId: options.clientId, nonce, ...keys });
|
|
74
|
+
const buildAuthorizationUrl = async (args) => {
|
|
75
|
+
const scopes = args.scope.split(" ").filter((scope) => scope !== "");
|
|
76
|
+
const optional = {
|
|
77
|
+
resource: args.resource,
|
|
78
|
+
response_mode: args.responseMode,
|
|
79
|
+
prompt: args.prompt,
|
|
80
|
+
login_hint: args.loginHint,
|
|
81
|
+
max_age: args.maxAge?.toString(),
|
|
82
|
+
organization: args.organizationId
|
|
83
|
+
};
|
|
84
|
+
const url = new URL(endpoints.authorizationEndpoint);
|
|
85
|
+
url.search = new URLSearchParams({
|
|
86
|
+
...args.extraParams,
|
|
87
|
+
...Object.fromEntries(Object.entries(optional).filter((entry) => entry[1] != null)),
|
|
88
|
+
response_type: "code",
|
|
89
|
+
client_id: options.clientId,
|
|
90
|
+
redirect_uri: options.redirectUri,
|
|
91
|
+
scope: [.../* @__PURE__ */ new Set(["openid", ...scopes])].join(" "),
|
|
92
|
+
state: args.state,
|
|
93
|
+
nonce: args.nonce,
|
|
94
|
+
code_challenge: await oauth.calculatePKCECodeChallenge(args.codeVerifier),
|
|
95
|
+
code_challenge_method: "S256"
|
|
96
|
+
}).toString();
|
|
97
|
+
return url;
|
|
98
|
+
};
|
|
99
|
+
const createAuthorizationRequest = async (args) => {
|
|
100
|
+
const checks = {
|
|
101
|
+
expectedState: randomState(),
|
|
102
|
+
expectedNonce: randomNonce(),
|
|
103
|
+
pkceCodeVerifier: randomPKCECodeVerifier(),
|
|
104
|
+
...args.maxAge == null ? {} : { maxAge: args.maxAge },
|
|
105
|
+
...args.organizationId == null ? {} : { expectedOrganizationId: args.organizationId }
|
|
106
|
+
};
|
|
107
|
+
const url = await buildAuthorizationUrl({
|
|
108
|
+
...args,
|
|
109
|
+
state: checks.expectedState,
|
|
110
|
+
nonce: checks.expectedNonce,
|
|
111
|
+
codeVerifier: checks.pkceCodeVerifier
|
|
112
|
+
});
|
|
113
|
+
return { url, checks };
|
|
114
|
+
};
|
|
115
|
+
const authorizationCodeGrant = async (callback, checks) => {
|
|
116
|
+
const params = callback instanceof URLSearchParams ? callback : URL.parse(callback, options.redirectUri)?.searchParams;
|
|
117
|
+
if (params == null) return failed("invalid_callback" /* InvalidCallback */);
|
|
118
|
+
let validated;
|
|
119
|
+
try {
|
|
120
|
+
validated = oauth.validateAuthResponse(server, client, params, checks.expectedState);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (error instanceof oauth.AuthorizationResponseError)
|
|
123
|
+
return oauthError(
|
|
124
|
+
error.error === "access_denied" ? "access_denied" /* AccessDenied */ : LOGIN_REQUIRED.includes(error.error) ? "login_required" /* LoginRequired */ : "authorization_error" /* AuthorizationError */,
|
|
125
|
+
error
|
|
126
|
+
);
|
|
127
|
+
return failed(
|
|
128
|
+
params.get("iss") === options.issuer ? "state_mismatch" /* StateMismatch */ : "issuer_mismatch" /* IssuerMismatch */
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
const requestedAt = Date.now();
|
|
132
|
+
let response;
|
|
133
|
+
try {
|
|
134
|
+
response = await oauth.authorizationCodeGrantRequest(
|
|
135
|
+
server,
|
|
136
|
+
client,
|
|
137
|
+
auth,
|
|
138
|
+
validated,
|
|
139
|
+
options.redirectUri,
|
|
140
|
+
checks.pkceCodeVerifier,
|
|
141
|
+
http
|
|
142
|
+
);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
return failed(
|
|
145
|
+
error instanceof oauth.OperationProcessingError ? "invalid_callback" /* InvalidCallback */ : "token_endpoint_unavailable" /* TokenEndpointUnavailable */
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
const body = response.clone();
|
|
149
|
+
const json = await body.json().catch(() => null);
|
|
150
|
+
let tokens = null;
|
|
151
|
+
let maxAgeExceeded = false;
|
|
152
|
+
try {
|
|
153
|
+
tokens = await oauth.processAuthorizationCodeResponse(server, client, response, {
|
|
154
|
+
expectedNonce: checks.expectedNonce,
|
|
155
|
+
requireIdToken: true,
|
|
156
|
+
...checks.maxAge == null ? {} : { maxAge: checks.maxAge }
|
|
157
|
+
});
|
|
158
|
+
} catch (error) {
|
|
159
|
+
if (error instanceof oauth.ResponseBodyError)
|
|
160
|
+
return oauthError("token_error" /* TokenError */, error);
|
|
161
|
+
const challenge = error instanceof oauth.WWWAuthenticateChallengeError ? error.cause[0]?.parameters : null;
|
|
162
|
+
if (challenge?.error != null)
|
|
163
|
+
return oauthError("token_error" /* TokenError */, { ...challenge, error: challenge.error });
|
|
164
|
+
maxAgeExceeded = error instanceof oauth.OperationProcessingError && error.code === oauth.JWT_TIMESTAMP_CHECK && typeof error.cause === "object" && error.cause != null && "claim" in error.cause && error.cause.claim === "auth_time";
|
|
165
|
+
}
|
|
166
|
+
const idToken = json?.id_token;
|
|
167
|
+
const verified = typeof idToken === "string" ? await verify(idToken, checks.expectedNonce) : null;
|
|
168
|
+
if (verified?.ok === false)
|
|
169
|
+
return { ok: false, failure: "invalid_id_token" /* InvalidIdToken */, refusal: verified.refusal };
|
|
170
|
+
if (maxAgeExceeded) return failed("max_age_exceeded" /* MaxAgeExceeded */);
|
|
171
|
+
if (tokens == null || verified == null || typeof idToken !== "string")
|
|
172
|
+
return failed("invalid_response" /* InvalidResponse */);
|
|
173
|
+
if (checks.expectedOrganizationId != null && verified.claims.organizationId !== checks.expectedOrganizationId)
|
|
174
|
+
return failed("organization_mismatch" /* OrganizationMismatch */);
|
|
175
|
+
return {
|
|
176
|
+
ok: true,
|
|
177
|
+
claims: verified.claims,
|
|
178
|
+
idToken,
|
|
179
|
+
accessToken: tokens.access_token,
|
|
180
|
+
expiresAt: tokens.expires_in == null ? null : requestedAt + tokens.expires_in * 1e3,
|
|
181
|
+
refreshToken: tokens.refresh_token ?? null,
|
|
182
|
+
scope: tokens.scope ?? null
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
return { createAuthorizationRequest, buildAuthorizationUrl, authorizationCodeGrant };
|
|
186
|
+
};
|
|
187
|
+
export {
|
|
188
|
+
SignInFailure,
|
|
189
|
+
TokenRefusal2 as TokenRefusal,
|
|
190
|
+
createSignInClient,
|
|
191
|
+
finalSignInEndpoints,
|
|
192
|
+
getVisitor,
|
|
193
|
+
randomNonce,
|
|
194
|
+
randomPKCECodeVerifier,
|
|
195
|
+
randomState,
|
|
196
|
+
verifyIdToken2 as verifyIdToken
|
|
197
|
+
};
|
|
198
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n JWKS_PATH,\n remoteJwks,\n TokenRefusal,\n verifyIdToken,\n type IdTokenIface,\n type JwksIface,\n type JwksKeySourceIface,\n} from '@finalai/agent-protocol/identity';\nimport * as oauth from 'oauth4webapi';\n\n// Sign in with Final: the OpenID Connect authorization code flow with PKCE against Final's\n// authorization server, on oauth4webapi. This adds only Final's defaults (its endpoints until it\n// publishes discovery, `openid` in every scope, `iss` always required, EdDSA ID tokens, a client\n// assertion from a private JWK, `resource`) and typed results. Names follow openid-client.\n// WebCrypto, fetch and URL only: Node, Workers, Deno and browsers.\n\nexport {\n getVisitor,\n TokenRefusal,\n verifyIdToken,\n type GetVisitorOptionsIface,\n type IdTokenIface,\n type VisitorActorIface,\n type VisitorIface,\n} from '@finalai/agent-protocol/identity';\n\nexport const randomState = oauth.generateRandomState;\nexport const randomNonce = oauth.generateRandomNonce;\nexport const randomPKCECodeVerifier = oauth.generateRandomCodeVerifier;\n\nexport interface SignInEndpointsIface {\n authorizationEndpoint: string;\n tokenEndpoint: string;\n jwksUri: string;\n}\n\n/** Final's endpoints under an issuer, until it publishes OpenID Connect discovery. */\nexport const finalSignInEndpoints = (issuer: string): SignInEndpointsIface => ({\n authorizationEndpoint: `${issuer}/oauth/authorize`,\n tokenEndpoint: `${issuer}/oauth/token`,\n jwksUri: `${issuer}${JWKS_PATH}`,\n});\n\nexport interface SignInClientOptionsIface {\n /** The authorization server's origin, e.g. `https://auth.control.final.ai`. */\n issuer: string;\n clientId: string;\n /** Exactly as registered. */\n redirectUri: string;\n /** Defaults to `finalSignInEndpoints(issuer)`. */\n endpoints?: SignInEndpointsIface;\n /**\n * The private JWK registered for private_key_jwt (Ed25519, P-256 or RSA); omit for a public\n * client, which authenticates with PKCE alone.\n */\n clientPrivateJwk?: JsonWebKey & { kid?: string };\n fetch?: typeof fetch;\n /** The issuer's keys; defaults to fetching and caching `endpoints.jwksUri`. */\n jwks?: JwksIface | JwksKeySourceIface;\n}\n\n/** What a sign-in asks for; `createAuthorizationRequest` takes these alone. */\nexport interface AuthorizationRequestArgsIface {\n /** Space-separated; `openid` is added when missing. */\n scope: string;\n /** RFC 8707: the origin to get an access token for (a private site's own origin). */\n resource?: string;\n responseMode?: 'query' | 'form_post';\n /** `none` signs in only without any interaction, else fails with `login_required`. */\n prompt?: 'none' | 'login' | 'consent';\n loginHint?: string;\n /** Seconds since the person last authenticated; the grant checks the ID token's `auth_time`. */\n maxAge?: number;\n /** The organization to sign in under (`organization`); the grant checks the ID token's `org`. */\n organizationId?: string;\n /** Further parameters; they never replace one this sets. */\n extraParams?: Record<string, string>;\n}\n\nexport interface AuthorizationUrlArgsIface extends AuthorizationRequestArgsIface {\n /** From `randomState()`, kept with the browser until the callback, as are the next two. */\n state: string;\n nonce: string;\n /** From `randomPKCECodeVerifier()`; the URL carries its S256 challenge. */\n codeVerifier: string;\n}\n\n/** What `authorizationCodeGrant` checks: keep it with the browser until the callback. */\nexport interface AuthorizationChecksIface {\n expectedState: string;\n expectedNonce: string;\n pkceCodeVerifier: string;\n maxAge?: number;\n expectedOrganizationId?: string;\n}\n\n/**\n * Why a sign-in failed. Closed: a new value is a breaking change. An OAuth error code with no\n * value of its own arrives as `authorization_error` or `token_error`, with the code in `error`.\n */\nexport enum SignInFailure {\n InvalidCallback = 'invalid_callback',\n // RFC 9207: `iss` missing or another issuer's.\n IssuerMismatch = 'issuer_mismatch',\n StateMismatch = 'state_mismatch',\n // The person declined (`access_denied`).\n AccessDenied = 'access_denied',\n // Signing in needs the person (`login_required`, `interaction_required`, `consent_required`,\n // `account_selection_required`), as after `prompt=none`.\n LoginRequired = 'login_required',\n // Any other OAuth error from the authorization endpoint.\n AuthorizationError = 'authorization_error',\n TokenEndpointUnavailable = 'token_endpoint_unavailable',\n // The token endpoint answered with an OAuth error (`error`, e.g. invalid_grant).\n TokenError = 'token_error',\n // The ID token did not verify (`refusal`).\n InvalidIdToken = 'invalid_id_token',\n // The person last authenticated longer ago than `maxAge` allows.\n MaxAgeExceeded = 'max_age_exceeded',\n // The ID token's `org` is not `expectedOrganizationId`.\n OrganizationMismatch = 'organization_mismatch',\n // Any other non-conforming token response.\n InvalidResponse = 'invalid_response',\n}\n\ntype OAuthFailure =\n | SignInFailure.AccessDenied\n | SignInFailure.LoginRequired\n | SignInFailure.AuthorizationError\n | SignInFailure.TokenError;\n// The failures that carry nothing more.\ntype PlainFailure = Exclude<SignInFailure, OAuthFailure | SignInFailure.InvalidIdToken>;\n\nexport type SignInResultType =\n | {\n ok: true;\n /** The verified ID token's claims: `subject` is the person's Final user ID. */\n claims: IdTokenIface;\n idToken: string;\n /** For the sign-in's `resource`, or else for userinfo. */\n accessToken: string;\n /** Milliseconds since the epoch, like `IdTokenIface`; null when the response gave none. */\n expiresAt: number | null;\n /** Null: Final issues no refresh tokens yet. */\n refreshToken: string | null;\n scope: string | null;\n }\n | { ok: false; failure: OAuthFailure; error: string; errorDescription: string | null }\n | { ok: false; failure: SignInFailure.InvalidIdToken; refusal: TokenRefusal }\n | { ok: false; failure: PlainFailure };\n\nexport interface SignInClientIface {\n /** A sign-in's URL, with its state, nonce and verifier made and returned as `checks`. */\n createAuthorizationRequest(\n args: AuthorizationRequestArgsIface,\n ): Promise<{ url: URL; checks: AuthorizationChecksIface }>;\n buildAuthorizationUrl(args: AuthorizationUrlArgsIface): Promise<URL>;\n /** The callback: its URL (relative resolves against the redirect URI), or a form_post body. */\n authorizationCodeGrant(\n callback: string | URL | URLSearchParams,\n checks: AuthorizationChecksIface,\n ): Promise<SignInResultType>;\n}\n\n// Web Crypto parameters by key type; oauth4webapi derives the JWS `alg` from the imported key.\nconst importParams = (jwk: JsonWebKey): RsaHashedImportParams | EcKeyImportParams | Algorithm =>\n jwk.kty === 'RSA'\n ? { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }\n : jwk.kty === 'EC'\n ? { name: 'ECDSA', namedCurve: 'P-256' }\n : { name: 'Ed25519' };\n\nconst clientAuthOf = async (\n jwk: SignInClientOptionsIface['clientPrivateJwk'],\n): Promise<oauth.ClientAuth> => {\n if (jwk == null) return oauth.None();\n const { kid, alg: _alg, key_ops: _ops, use: _use, ...members } = jwk;\n const key = await crypto.subtle.importKey('jwk', members, importParams(jwk), false, ['sign']);\n return oauth.PrivateKeyJwt(kid == null ? key : { key, kid });\n};\n\nconst LOGIN_REQUIRED = [\n 'login_required',\n 'interaction_required',\n 'consent_required',\n 'account_selection_required',\n];\n\nconst failed = (failure: PlainFailure): SignInResultType => ({ ok: false, failure });\n\n// An OAuth error from the authorization or token endpoint.\nconst oauthError = (\n failure: OAuthFailure,\n error: { error: string; error_description?: string },\n): SignInResultType => ({\n ok: false,\n failure,\n error: error.error,\n errorDescription: error.error_description ?? null,\n});\n\n/**\n * A client for one registered redirect URI. It imports `clientPrivateJwk` first, and rejects when\n * that is not a usable private key: a configuration error, unlike every sign-in's outcome.\n */\nexport const createSignInClient = async (\n options: SignInClientOptionsIface,\n): Promise<SignInClientIface> => {\n const auth = await clientAuthOf(options.clientPrivateJwk);\n const endpoints = options.endpoints ?? finalSignInEndpoints(options.issuer);\n // Final's metadata, which its OpenID Connect discovery document will carry once it is published:\n // `iss` on every authorization response, and EdDSA ID tokens.\n const server: oauth.AuthorizationServer = {\n issuer: options.issuer,\n authorization_endpoint: endpoints.authorizationEndpoint,\n token_endpoint: endpoints.tokenEndpoint,\n jwks_uri: endpoints.jwksUri,\n authorization_response_iss_parameter_supported: true,\n };\n const client: oauth.Client = {\n client_id: options.clientId,\n id_token_signed_response_alg: 'EdDSA',\n };\n const doFetch = options.fetch;\n const http = doFetch == null ? {} : { [oauth.customFetch]: doFetch };\n // Without a fetch of its own, the key set is cached per URL across the process.\n const keys =\n options.jwks != null\n ? { jwks: options.jwks }\n : doFetch == null\n ? { jwksUrl: endpoints.jwksUri }\n : { jwks: remoteJwks({ url: endpoints.jwksUri, fetch: doFetch }) };\n\n const verify = (token: string, nonce: string) =>\n verifyIdToken({ token, issuer: options.issuer, clientId: options.clientId, nonce, ...keys });\n\n const buildAuthorizationUrl = async (args: AuthorizationUrlArgsIface): Promise<URL> => {\n const scopes = args.scope.split(' ').filter((scope) => scope !== '');\n const optional = {\n resource: args.resource,\n response_mode: args.responseMode,\n prompt: args.prompt,\n login_hint: args.loginHint,\n max_age: args.maxAge?.toString(),\n organization: args.organizationId,\n };\n const url = new URL(endpoints.authorizationEndpoint);\n url.search = new URLSearchParams({\n ...args.extraParams,\n ...Object.fromEntries(Object.entries(optional).filter((entry) => entry[1] != null)),\n response_type: 'code',\n client_id: options.clientId,\n redirect_uri: options.redirectUri,\n scope: [...new Set(['openid', ...scopes])].join(' '),\n state: args.state,\n nonce: args.nonce,\n code_challenge: await oauth.calculatePKCECodeChallenge(args.codeVerifier),\n code_challenge_method: 'S256',\n }).toString();\n return url;\n };\n\n const createAuthorizationRequest = async (args: AuthorizationRequestArgsIface) => {\n const checks: AuthorizationChecksIface = {\n expectedState: randomState(),\n expectedNonce: randomNonce(),\n pkceCodeVerifier: randomPKCECodeVerifier(),\n ...(args.maxAge == null ? {} : { maxAge: args.maxAge }),\n ...(args.organizationId == null ? {} : { expectedOrganizationId: args.organizationId }),\n };\n const url = await buildAuthorizationUrl({\n ...args,\n state: checks.expectedState,\n nonce: checks.expectedNonce,\n codeVerifier: checks.pkceCodeVerifier,\n });\n return { url, checks };\n };\n\n const authorizationCodeGrant = async (\n callback: string | URL | URLSearchParams,\n checks: AuthorizationChecksIface,\n ): Promise<SignInResultType> => {\n const params =\n callback instanceof URLSearchParams\n ? callback\n : URL.parse(callback, options.redirectUri)?.searchParams;\n if (params == null) return failed(SignInFailure.InvalidCallback);\n let validated: URLSearchParams;\n try {\n validated = oauth.validateAuthResponse(server, client, params, checks.expectedState);\n } catch (error) {\n if (error instanceof oauth.AuthorizationResponseError)\n return oauthError(\n error.error === 'access_denied'\n ? SignInFailure.AccessDenied\n : LOGIN_REQUIRED.includes(error.error)\n ? SignInFailure.LoginRequired\n : SignInFailure.AuthorizationError,\n error,\n );\n // oauth4webapi checks `iss` before `state`.\n return failed(\n params.get('iss') === options.issuer\n ? SignInFailure.StateMismatch\n : SignInFailure.IssuerMismatch,\n );\n }\n const requestedAt = Date.now();\n let response: Response;\n try {\n response = await oauth.authorizationCodeGrantRequest(\n server,\n client,\n auth,\n validated,\n options.redirectUri,\n checks.pkceCodeVerifier,\n http,\n );\n } catch (error) {\n // oauth4webapi refuses a callback without exactly one `code` before it sends anything.\n return failed(\n error instanceof oauth.OperationProcessingError\n ? SignInFailure.InvalidCallback\n : SignInFailure.TokenEndpointUnavailable,\n );\n }\n const body = response.clone();\n const json: Record<string, unknown> | null = await body.json().catch(() => null);\n let tokens: oauth.TokenEndpointResponse | null = null;\n let maxAgeExceeded = false;\n try {\n tokens = await oauth.processAuthorizationCodeResponse(server, client, response, {\n expectedNonce: checks.expectedNonce,\n requireIdToken: true,\n ...(checks.maxAge == null ? {} : { maxAge: checks.maxAge }),\n });\n } catch (error) {\n if (error instanceof oauth.ResponseBodyError)\n return oauthError(SignInFailure.TokenError, error);\n // A 401 with `WWW-Authenticate` carries its OAuth error in the challenge.\n const challenge =\n error instanceof oauth.WWWAuthenticateChallengeError ? error.cause[0]?.parameters : null;\n if (challenge?.error != null)\n return oauthError(SignInFailure.TokenError, { ...challenge, error: challenge.error });\n maxAgeExceeded =\n error instanceof oauth.OperationProcessingError &&\n error.code === oauth.JWT_TIMESTAMP_CHECK &&\n typeof error.cause === 'object' &&\n error.cause != null &&\n 'claim' in error.cause &&\n error.cause.claim === 'auth_time';\n }\n // oauth4webapi checks an ID token's claims, not its signature: verify it against the JWKS,\n // which also says why one it refused (the nonce, say) is not this sign-in's.\n const idToken = json?.id_token;\n const verified =\n typeof idToken === 'string' ? await verify(idToken, checks.expectedNonce) : null;\n if (verified?.ok === false)\n return { ok: false, failure: SignInFailure.InvalidIdToken, refusal: verified.refusal };\n if (maxAgeExceeded) return failed(SignInFailure.MaxAgeExceeded);\n if (tokens == null || verified == null || typeof idToken !== 'string')\n return failed(SignInFailure.InvalidResponse);\n if (\n checks.expectedOrganizationId != null &&\n verified.claims.organizationId !== checks.expectedOrganizationId\n )\n return failed(SignInFailure.OrganizationMismatch);\n return {\n ok: true,\n claims: verified.claims,\n idToken,\n accessToken: tokens.access_token,\n expiresAt: tokens.expires_in == null ? null : requestedAt + tokens.expires_in * 1000,\n refreshToken: tokens.refresh_token ?? null,\n scope: tokens.scope ?? null,\n };\n };\n\n return { createAuthorizationRequest, buildAuthorizationUrl, authorizationCodeGrant };\n};\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,YAAY,WAAW;AAQvB;AAAA,EACE;AAAA,EACA,gBAAAA;AAAA,EACA,iBAAAC;AAAA,OAKK;AAEA,MAAM,cAAc,MAAM;AAC1B,MAAM,cAAc,MAAM;AAC1B,MAAM,yBAAyB,MAAM;AASrC,MAAM,uBAAuB,CAAC,YAA0C;AAAA,EAC7E,uBAAuB,GAAG,MAAM;AAAA,EAChC,eAAe,GAAG,MAAM;AAAA,EACxB,SAAS,GAAG,MAAM,GAAG,SAAS;AAChC;AA2DO,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,qBAAkB;AAElB,EAAAA,eAAA,oBAAiB;AACjB,EAAAA,eAAA,mBAAgB;AAEhB,EAAAA,eAAA,kBAAe;AAGf,EAAAA,eAAA,mBAAgB;AAEhB,EAAAA,eAAA,wBAAqB;AACrB,EAAAA,eAAA,8BAA2B;AAE3B,EAAAA,eAAA,gBAAa;AAEb,EAAAA,eAAA,oBAAiB;AAEjB,EAAAA,eAAA,oBAAiB;AAEjB,EAAAA,eAAA,0BAAuB;AAEvB,EAAAA,eAAA,qB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BAAiB;AAAA,MACtC,OAAO,OAAO,SAAS;AAAA,IACzB;AAAA,EACF;AAEA,SAAO,EAAE,4BAA4B,uBAAuB,uBAAuB;AACrF;",
|
|
6
|
+
"names": ["TokenRefusal", "verifyIdToken", "SignInFailure"]
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@finalai/sign-in",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Sign in with Final: an OpenID Connect client for Final's authorization server, and the verifiers apps and resource servers need.",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md",
|
|
10
|
+
"LICENSE",
|
|
11
|
+
"NOTICE",
|
|
12
|
+
"HOSTING.md"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"types": "./dist/modules/index.d.mts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/modules/index.d.mts",
|
|
20
|
+
"import": "./dist/modules/index.mjs",
|
|
21
|
+
"default": "./dist/modules/index.mjs"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public",
|
|
27
|
+
"registry": "https://registry.npmjs.org/"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@finalai/agent-protocol": "0.23.0",
|
|
31
|
+
"oauth4webapi": "3.8.8"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=26"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/final-company/packages-typescript.git",
|
|
39
|
+
"directory": "packages/@finalai/sign-in"
|
|
40
|
+
}
|
|
41
|
+
}
|