@jaccard-ai/eve-auth 0.0.0 → 0.2.2-rc.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/README.md CHANGED
@@ -1,3 +1,230 @@
1
1
  # @jaccard-ai/eve-auth
2
2
 
3
- Placeholder. See https://www.jaccard.ai
3
+ Route auth for [eve](https://eve.dev) agents running on the Jaccard platform.
4
+
5
+ The platform's gateway asks an auth service about every request to an agent's
6
+ session routes. The service checks the caller's Jaccard token, its organization
7
+ and the agent's `jaccard.toml`, and passes an allowed request on with a
8
+ short-lived identity token in the header `x-jaccard-identity`. `jaccardOidc()`
9
+ is one entry of an agent's authenticator chain. It verifies that identity token
10
+ and gives eve the caller's identity record from it. It declines everything
11
+ else, and eve answers `401`.
12
+
13
+ The [overview](../../../docs/eve-auth/overview.md) walks one developer through
14
+ all of it: protecting an agent, connecting as a member, and putting a web back
15
+ end in front of it. The numbered specs in
16
+ [`docs/eve-auth`](../../../docs/eve-auth/README.md) are the reference. If this
17
+ README and a spec disagree, the spec is correct.
18
+
19
+ ## Installing
20
+
21
+ The package is published to npmjs.org, so no `.npmrc` is needed:
22
+
23
+ ```sh
24
+ pnpm add @jaccard-ai/eve-auth
25
+ ```
26
+
27
+ eve 0.78.0 or later is a peer dependency: the tool-stub grant and the
28
+ forwarder check need it, and eve 0.78 needs Node 24, so this package does too.
29
+ One release serves both eve lines (`>=0.78.0 || >=1.0.0-rc.8`): the source
30
+ type-checks and its tests pass against eve 0.78.0 and 1.0.0-rc.8. While eve
31
+ 1.0 is a release candidate, the releases built and tested for it (0.2.2-rc.N)
32
+ are on the npm `next` dist-tag (`pnpm add @jaccard-ai/eve-auth@next`), and
33
+ `latest` stays on 0.2.1. `@jaccard-ai/eve-sandbox` and
34
+ `@jaccard-ai/eve-metrics` each have one line per eve minor; install the ones
35
+ that match the agent's eve.
36
+
37
+ From 0.2.2 every key set fetch sends `x-jaccard-client:
38
+ @jaccard-ai/eve-auth@<version> eve@<version>` (JAC-2967), so the platform can
39
+ tell which releases deployed agents still run.
40
+
41
+ Releases are cut from CI by a tag (`eve-auth-v<version>`), never by a local
42
+ `pnpm publish`: `docs/runbooks/eve-packages-npm.md`.
43
+
44
+ An agent project whose `.npmrc` still maps `@jaccard-ai` to the self-hosted
45
+ registry keeps working: that registry has every release too.
46
+
47
+ ## Protect an agent
48
+
49
+ Write the agent's HTTP channel file. Authoring it at all is the point: eve's
50
+ default chain, `[vercelOidc(), localDev(), placeholderAuth()]`, declines on the
51
+ Jaccard platform, so without this file every request is refused.
52
+
53
+ ```ts
54
+ // agent/channels/eve.ts
55
+ import { eveChannel } from "eve/channels/eve";
56
+ import { localDev } from "eve/channels/auth";
57
+ import { jaccardOidc } from "@jaccard-ai/eve-auth";
58
+
59
+ export default eveChannel({
60
+ auth: [localDev(), jaccardOidc()],
61
+ });
62
+ ```
63
+
64
+ - On a laptop (`eve dev`), `localDev()` admits every request as `local-dev`.
65
+ No token and no Jaccard setting is needed.
66
+ - In the pod, `localDev()` always declines, so `jaccardOidc()` decides. The
67
+ operator has already put the agent's organization, its name and the identity
68
+ key set location there. The author sets none of them.
69
+ - Who is admitted is the platform's decision, from the `callers` list of the
70
+ agent's `jaccard.toml`
71
+ ([spec 08](../../../docs/eve-auth/08-agent-access-policy.md)), not the
72
+ package's. The package takes no subject patterns.
73
+ - A request that reaches the agent without the gateway carries no identity
74
+ token, so the agent declines it. The agent never sees a caller's own token:
75
+ the gateway removes `authorization`.
76
+ - Keep `localDev()` first. With `jaccardOidc()` first, a laptop has no Jaccard
77
+ settings, so every local request gets the setup refusal.
78
+
79
+ A decline is never a `403`. The chain's `401` advertises `Bearer`, and the
80
+ reason goes only to the agent's debug log ([Debugging](#debugging-a-refusal)).
81
+
82
+ ## Let a service speak for its users
83
+
84
+ A developer service that sits between its users and an agent can forward each
85
+ user. The service needs an entry in both the `callers` and the `forwarders`
86
+ lists of `jaccard.toml`, and the channel file trusts the forwarders:
87
+
88
+ ```ts
89
+ import { eveChannel } from "eve/channels/eve";
90
+ import { localDev } from "eve/channels/auth";
91
+ import { jaccardForwarders, jaccardOidc } from "@jaccard-ai/eve-auth";
92
+
93
+ export default eveChannel({
94
+ auth: [localDev(), jaccardOidc()],
95
+ trustedForwarders: jaccardForwarders(),
96
+ });
97
+ ```
98
+
99
+ `jaccardForwarders()` takes no options. It trusts a forwarder only when its
100
+ record is a `service` of `jaccard-oidc` that carries the attribute
101
+ `jaccard:forwarder` with the value `true`, which the auth service sets for a
102
+ service in `forwarders`. It accepts only `user` records whose `tenant`
103
+ attribute is the agent's organization, and refuses every other asserted record.
104
+ A refusal returns `false`, and eve answers `403`.
105
+
106
+ It reads the agent's organization from `JACCARD_TENANT` and from nowhere else.
107
+ An organization passed only as `jaccardOidc({ tenant })` does not reach it, so
108
+ without `JACCARD_TENANT` it refuses every forwarded user as `wrong-tenant`,
109
+ although `jaccardOidc()` admits the service. The operator sets the setting in
110
+ every pod of a `tenant-<organization>` namespace.
111
+
112
+ A service in the `tool_stubs` list gets the tool-stub grant: the acceptance
113
+ carries `allowToolStubs: true`, which eve checks on `stubs`.
114
+
115
+ [`examples/channel.ts`](examples/channel.ts) is this channel file in full.
116
+
117
+ ## Call another agent
118
+
119
+ An agent calls another agent's routes with its own workload token. The helper
120
+ under `@jaccard-ai/eve-auth/agents` reads the token file on every request and
121
+ sends it as a bearer:
122
+
123
+ ```ts
124
+ // agent/subagents/support.ts
125
+ import { defineRemoteAgent } from "eve";
126
+ import { jaccardOidc } from "@jaccard-ai/eve-auth/agents";
127
+
128
+ export default defineRemoteAgent({
129
+ url: "https://support-acme.jaccard.app",
130
+ description: "Answers customer support questions.",
131
+ auth: jaccardOidc(),
132
+ });
133
+ ```
134
+
135
+ Point `url` at the target's public hostname,
136
+ `https://<agent>-<organization>.jaccard.app`, so the call passes the gateway.
137
+ The target admits it only when its `callers` list names the calling agent
138
+ (`tenant:<organization>:agent:<name>`), unless the target is the calling agent
139
+ itself. The helper takes the path from `JACCARD_WORKLOAD_TOKEN_FILE`, or from its
140
+ `tokenFile` option. When it cannot read a token it throws an error that names
141
+ the setting or the path, and never the token.
142
+
143
+ ## Exports
144
+
145
+ | Export | Import from | Use |
146
+ |---|---|---|
147
+ | `jaccardOidc(options?)` | `@jaccard-ai/eve-auth` | The route authenticator, for the `auth` array of `eveChannel()`. |
148
+ | `jaccardForwarders()` | `@jaccard-ai/eve-auth` | The `trustedForwarders` check. |
149
+ | `jaccardOidc(options?)` | `@jaccard-ai/eve-auth/agents` | The outbound credential for `defineRemoteAgent()`. Its one option is `tokenFile`. |
150
+
151
+ `@jaccard-ai/eve-auth` also exports the type `JaccardOidcOptions`.
152
+ `@jaccard-ai/eve-auth/agents` exports its own `JaccardOidcOptions`. The two
153
+ `jaccardOidc` functions are different: the first guards routes and the second
154
+ signs outbound calls.
155
+
156
+ To upgrade from the 0.0.2 mock, rebuild the agent with 0.2.0. The mock keeps
157
+ working behind the gateway check until then.
158
+
159
+ ## Settings
160
+
161
+ The operator sets these settings in every agent pod, except that
162
+ `JACCARD_TENANT` is set only in a `tenant-<organization>` namespace
163
+ ([spec 01](../../../docs/eve-auth/01-agent-identity-provisioning.md)).
164
+ `EVE_LOG_LEVEL` is eve's own log threshold, which the author sets. An author
165
+ sets none of the others, and passes an option only to override one.
166
+
167
+ | Setting | Option | Required |
168
+ |---|---|---|
169
+ | `JACCARD_TENANT` | `tenant` | yes: 1 to 56 lower-case letters, digits and `-`, with no `-` at either end |
170
+ | `EVE_AGENT_NAME` | `agentName` | yes: not empty, no `:` |
171
+ | `JACCARD_IDENTITY_JWKS_URL` | `identityJwksUrl` | yes: an `https` URL |
172
+ | `JACCARD_WORKLOAD_TOKEN_FILE` | `tokenFile`, in `@jaccard-ai/eve-auth/agents` | for outbound calls |
173
+ | `EVE_LOG_LEVEL` | none | `debug` turns the diagnostics on |
174
+
175
+ An option wins over its setting, one value at a time. Surrounding whitespace is
176
+ removed, and an option that is empty after that falls back to the
177
+ setting. A value that is still empty counts as missing. An invalid option does not fall
178
+ back to the setting.
179
+
180
+ The authenticator reads its settings on every request, before it reads the
181
+ identity header. When a required one is missing or invalid, every request gets
182
+ a `401` with the code `jaccard_auth_not_configured`, whose message names each
183
+ such setting and never a value. The package also warns once on the console. An
184
+ agent outside a `tenant-<organization>` namespace has no `JACCARD_TENANT`, and
185
+ refuses every request this way unless its author passes the `tenant` option.
186
+
187
+ ## What it checks
188
+
189
+ - **Header.** Only `x-jaccard-identity`, never `authorization`. Without it the
190
+ authenticator declines at once, with no network call and no log line. An
191
+ empty value counts as present and is declined as `malformed`.
192
+ - **Signature.** `ES256` only, with the key of the identity key set whose `kid`
193
+ matches. The key set is fetched from `JACCARD_IDENTITY_JWKS_URL` with no
194
+ redirects and a 5 second limit. It is cached for 10 minutes, and refetched
195
+ for an unknown `kid` at most every 30 seconds.
196
+ - **Claims.** `iss` is `https://jaccard.ai` and `aud` is
197
+ `tenant:<organization>:agent:<agent name>`. `exp` and `iat` are required,
198
+ with 30 seconds of clock tolerance, and a token is at most 90 seconds old,
199
+ plus the 30 seconds of tolerance. A future `nbf` is declined as
200
+ `invalid-signature`.
201
+ - **Identity record.** The `jaccard_identity` claim must be a record
202
+ (`principalId`, `principalType` and `authenticator` as non-empty strings,
203
+ optional `issuer` and `subject` non-empty strings, and `attributes` of strings or lists
204
+ of strings). eve receives it unchanged (a grant field inside it is ignored), plus `allowToolStubs: true` when the
205
+ token carries `jaccard_tool_stubs`.
206
+
207
+ ## Debugging a refusal
208
+
209
+ Set `EVE_LOG_LEVEL=debug` on the agent. Each identity token that reaches the
210
+ authenticator then writes one line to the console, with ids and a reason and
211
+ never the token:
212
+
213
+ ```
214
+ [@jaccard-ai/eve-auth] Rejected Jaccard identity token. { reason: 'wrong-audience', subject: 'tenant:acme:user:member-…' }
215
+ ```
216
+
217
+ The reasons are `malformed`, `key-set-unavailable`, `unknown-key`,
218
+ `invalid-signature`, `wrong-issuer`, `wrong-audience`, `expired`, `too-old` and
219
+ `invalid-identity`. The caller never sees one. `subject` is what the sender
220
+ wrote, decoded without verification. An accepted token writes
221
+ `Accepted Jaccard identity.` with the `subject` and `principalType`. A declined
222
+ identity token with the gateway in front points to a setting that does not
223
+ match the agent, or to a request that did not come through the gateway. The
224
+ reason a caller was refused at the gateway is only in the auth service's log.
225
+ `jaccardForwarders()` writes a line of its own, `Refused forwarded principal.`
226
+
227
+ ## License
228
+
229
+ Use of this software is subject to the
230
+ [Jaccard Terms of Service](https://www.jaccard.ai/terms-of-service).
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Outbound credentials for eve's remote-agent calls on the Jaccard platform.
3
+ *
4
+ * ```ts
5
+ * // agent/subagents/support.ts
6
+ * import { defineRemoteAgent } from "eve";
7
+ * import { jaccardOidc } from "@jaccard-ai/eve-auth/agents";
8
+ *
9
+ * export default defineRemoteAgent({
10
+ * url: "https://support-acme.jaccard.app",
11
+ * description: "Answers customer support questions.",
12
+ * auth: jaccardOidc(),
13
+ * });
14
+ * ```
15
+ */
16
+ import type { OutboundAuthFn } from 'eve/agents/auth';
17
+ export interface JaccardOidcOptions {
18
+ /** Path of the workload token file. Overrides `JACCARD_WORKLOAD_TOKEN_FILE`. */
19
+ readonly tokenFile?: string;
20
+ }
21
+ /**
22
+ * Returns an outbound auth function that sends the agent's workload token.
23
+ *
24
+ * The file is read again on every call and no copy is kept: the cluster
25
+ * replaces it before the token expires. The token is neither decoded nor
26
+ * checked, and no error message may repeat it.
27
+ */
28
+ export declare function jaccardOidc(options?: JaccardOidcOptions): OutboundAuthFn;
package/dist/agents.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Outbound credentials for eve's remote-agent calls on the Jaccard platform.
3
+ *
4
+ * ```ts
5
+ * // agent/subagents/support.ts
6
+ * import { defineRemoteAgent } from "eve";
7
+ * import { jaccardOidc } from "@jaccard-ai/eve-auth/agents";
8
+ *
9
+ * export default defineRemoteAgent({
10
+ * url: "https://support-acme.jaccard.app",
11
+ * description: "Answers customer support questions.",
12
+ * auth: jaccardOidc(),
13
+ * });
14
+ * ```
15
+ */
16
+ import { readFile } from 'node:fs/promises';
17
+ const TOKEN_FILE_SETTING = 'JACCARD_WORKLOAD_TOKEN_FILE';
18
+ /**
19
+ * Returns an outbound auth function that sends the agent's workload token.
20
+ *
21
+ * The file is read again on every call and no copy is kept: the cluster
22
+ * replaces it before the token expires. The token is neither decoded nor
23
+ * checked, and no error message may repeat it.
24
+ */
25
+ export function jaccardOidc(options = {}) {
26
+ return async () => {
27
+ const path = options.tokenFile || process.env[TOKEN_FILE_SETTING];
28
+ if (!path) {
29
+ throw new Error(`jaccardOidc: ${TOKEN_FILE_SETTING} is not set and no tokenFile option was given.`);
30
+ }
31
+ let contents;
32
+ try {
33
+ contents = await readFile(path, 'utf8');
34
+ }
35
+ catch (cause) {
36
+ throw new Error(`jaccardOidc: cannot read the agent token file at ${path}.`, { cause });
37
+ }
38
+ const token = contents.trim();
39
+ if (token.length === 0) {
40
+ throw new Error(`jaccardOidc: the agent token file at ${path} is empty.`);
41
+ }
42
+ return { headers: { authorization: `Bearer ${token}` } };
43
+ };
44
+ }
@@ -0,0 +1,7 @@
1
+ export declare const CLIENT_HEADER = "x-jaccard-client";
2
+ /** Built in, not read at runtime; client.test.ts holds it equal to package.json's. */
3
+ export declare const PACKAGE_VERSION = "0.2.2-rc.1";
4
+ /** `@jaccard-ai/eve-auth@<version>`, then `eve@<version>` when eve's manifest resolves. */
5
+ export declare function clientHeader(eveVersion: string | undefined): string;
6
+ /** eve's version from its own manifest; undefined where a bundle left eve out. */
7
+ export declare function installedEveVersion(): string | undefined;
package/dist/client.js ADDED
@@ -0,0 +1,27 @@
1
+ // The `x-jaccard-client` header (JAC-2967): which release of this package, and
2
+ // which eve, made a call, so the platform can tell which versions are still deployed.
3
+ import { createRequire } from 'node:module';
4
+ export const CLIENT_HEADER = 'x-jaccard-client';
5
+ /** Built in, not read at runtime; client.test.ts holds it equal to package.json's. */
6
+ export const PACKAGE_VERSION = '0.2.2-rc.1';
7
+ /** `@jaccard-ai/eve-auth@<version>`, then `eve@<version>` when eve's manifest resolves. */
8
+ export function clientHeader(eveVersion) {
9
+ const self = `@jaccard-ai/eve-auth@${PACKAGE_VERSION}`;
10
+ return eveVersion === undefined ? self : `${self} eve@${eveVersion}`;
11
+ }
12
+ /** eve's version from its own manifest; undefined where a bundle left eve out. */
13
+ export function installedEveVersion() {
14
+ try {
15
+ const manifest = createRequire(import.meta.url)('eve/package.json');
16
+ return hasVersion(manifest) ? manifest.version : undefined;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ function hasVersion(manifest) {
23
+ return (typeof manifest === 'object' &&
24
+ manifest !== null &&
25
+ 'version' in manifest &&
26
+ typeof manifest.version === 'string');
27
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The settings of the Jaccard authenticator (spec 18): where they come from,
3
+ * which of them are required, and the refusal for a missing or invalid one.
4
+ */
5
+ /** The resolved settings. */
6
+ export interface IdentitySettings {
7
+ tenant: string;
8
+ agentName: string;
9
+ identityJwksUrl: string;
10
+ }
11
+ /** Options that win over the settings, one value at a time. An empty value falls back. */
12
+ export interface JaccardOidcOptions {
13
+ readonly tenant?: string;
14
+ readonly agentName?: string;
15
+ readonly identityJwksUrl?: string;
16
+ }
17
+ type Env = Readonly<Record<string, string | undefined>>;
18
+ /**
19
+ * Resolves the settings from `options` and `env`, or raises the setup refusal.
20
+ * Call it on every request: spec 18 keeps nothing between requests.
21
+ */
22
+ export declare function resolveSettings(options?: JaccardOidcOptions, env?: Env): IdentitySettings;
23
+ /** The agent's organization from `JACCARD_TENANT` alone (spec 20 behavior 11); it never refuses or warns. */
24
+ export declare function agentTenant(env?: Env): string | undefined;
25
+ export {};
package/dist/config.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The settings of the Jaccard authenticator (spec 18): where they come from,
3
+ * which of them are required, and the refusal for a missing or invalid one.
4
+ */
5
+ import { UnauthenticatedError } from 'eve/channels/auth';
6
+ const TENANT = /^[a-z0-9](?:[a-z0-9-]{0,54}[a-z0-9])?$/;
7
+ // Module state on purpose: spec 18 warns once per loaded copy of the package,
8
+ // not once per call or per authenticator.
9
+ let warned = false;
10
+ /**
11
+ * Resolves the settings from `options` and `env`, or raises the setup refusal.
12
+ * Call it on every request: spec 18 keeps nothing between requests.
13
+ */
14
+ export function resolveSettings(options = {}, env = process.env) {
15
+ const missing = [];
16
+ const tenant = read(options.tenant, 'JACCARD_TENANT', env);
17
+ if (!isTenantName(tenant))
18
+ missing.push('JACCARD_TENANT');
19
+ const agentName = read(options.agentName, 'EVE_AGENT_NAME', env);
20
+ if (agentName === undefined || agentName.includes(':'))
21
+ missing.push('EVE_AGENT_NAME');
22
+ const identityJwksUrl = read(options.identityJwksUrl, 'JACCARD_IDENTITY_JWKS_URL', env);
23
+ if (identityJwksUrl === undefined || !isHttps(identityJwksUrl)) {
24
+ missing.push('JACCARD_IDENTITY_JWKS_URL');
25
+ }
26
+ if (missing.length > 0 || !tenant || !agentName || !identityJwksUrl) {
27
+ throw setupRefusal(missing);
28
+ }
29
+ return { tenant, agentName, identityJwksUrl };
30
+ }
31
+ /** The agent's organization from `JACCARD_TENANT` alone (spec 20 behavior 11); it never refuses or warns. */
32
+ export function agentTenant(env = process.env) {
33
+ const tenant = read(undefined, 'JACCARD_TENANT', env);
34
+ return isTenantName(tenant) ? tenant : undefined;
35
+ }
36
+ function isTenantName(value) {
37
+ return value !== undefined && TENANT.test(value);
38
+ }
39
+ /** The option if it has a value, else the setting if it has one. */
40
+ function read(option, setting, env) {
41
+ for (const raw of [option, env[setting]]) {
42
+ const value = typeof raw === 'string' ? raw.trim() : '';
43
+ if (value !== '')
44
+ return value;
45
+ }
46
+ return undefined;
47
+ }
48
+ function isHttps(value) {
49
+ try {
50
+ return new URL(value).protocol === 'https:';
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }
56
+ function setupRefusal(names) {
57
+ const list = names.join(', ');
58
+ if (!warned) {
59
+ warned = true;
60
+ console.warn(`[@jaccard-ai/eve-auth] Jaccard agent auth is not configured: ${list}. Every request is refused.`);
61
+ }
62
+ return new UnauthenticatedError({
63
+ challenges: [{ scheme: 'Bearer' }],
64
+ code: 'jaccard_auth_not_configured',
65
+ message: `Jaccard agent auth is not configured: ${list}.`,
66
+ });
67
+ }
@@ -0,0 +1,3 @@
1
+ /** The record values that the auth service writes and the forwarder check trusts (spec 19). */
2
+ export declare const AUTHENTICATOR = "jaccard-oidc";
3
+ export declare const ISSUER = "https://jaccard.ai";
@@ -0,0 +1,3 @@
1
+ /** The record values that the auth service writes and the forwarder check trusts (spec 19). */
2
+ export const AUTHENTICATOR = 'jaccard-oidc';
3
+ export const ISSUER = 'https://jaccard.ai';
@@ -0,0 +1,10 @@
1
+ /** Spec 22's gate and line format, for every debug line this package writes. */
2
+ /** A field without a value (undefined) is left out of the line. */
3
+ export type DiagnosticFields = Readonly<Record<string, string | undefined>>;
4
+ /** Read on every call: the threshold can change while the process runs. */
5
+ export declare function debugEnabled(): boolean;
6
+ /**
7
+ * Writes one line when the threshold is debug. A line carries ids and reasons
8
+ * only: never a token, and never a claim that spec 22 does not list.
9
+ */
10
+ export declare function debugLine(message: string, fields: DiagnosticFields): void;
@@ -0,0 +1,15 @@
1
+ /** Spec 22's gate and line format, for every debug line this package writes. */
2
+ /** Read on every call: the threshold can change while the process runs. */
3
+ export function debugEnabled() {
4
+ return process.env.EVE_LOG_LEVEL?.toLowerCase() === 'debug';
5
+ }
6
+ /**
7
+ * Writes one line when the threshold is debug. A line carries ids and reasons
8
+ * only: never a token, and never a claim that spec 22 does not list.
9
+ */
10
+ export function debugLine(message, fields) {
11
+ if (!debugEnabled())
12
+ return;
13
+ const present = Object.entries(fields).filter(([, value]) => value !== undefined);
14
+ console.debug(`[@jaccard-ai/eve-auth] ${message}`, Object.fromEntries(present));
15
+ }
@@ -0,0 +1,7 @@
1
+ /** The trusted-forwarders check (spec 20 behaviors 7-12): which services may speak for end users. */
2
+ import type { TrustedForwarders } from 'eve/channels/eve';
3
+ /**
4
+ * A refusal returns `false`: a throw becomes the host's 500. The organization
5
+ * and the log threshold are read on every call.
6
+ */
7
+ export declare function jaccardForwarders(): TrustedForwarders;
@@ -0,0 +1,47 @@
1
+ /** The trusted-forwarders check (spec 20 behaviors 7-12): which services may speak for end users. */
2
+ import { agentTenant } from './config.js';
3
+ import { AUTHENTICATOR, ISSUER } from './constants.js';
4
+ import { debugLine } from './diagnostics.js';
5
+ /**
6
+ * A refusal returns `false`: a throw becomes the host's 500. The organization
7
+ * and the log threshold are read on every call.
8
+ */
9
+ export function jaccardForwarders() {
10
+ return (forwarder, assertion) => {
11
+ const refusal = refusalOf(forwarder, assertion);
12
+ if (refusal === undefined)
13
+ return true;
14
+ logRefusal(refusal, forwarder, assertion);
15
+ return false;
16
+ };
17
+ }
18
+ function refusalOf(forwarder, assertion) {
19
+ if (!isTrustedForwarder(forwarder))
20
+ return 'untrusted-forwarder';
21
+ const tenant = agentTenant();
22
+ if (tenant === undefined)
23
+ return 'wrong-tenant';
24
+ if (assertion.principal === undefined)
25
+ return undefined;
26
+ for (const record of [assertion.principal.current, assertion.principal.initiator]) {
27
+ if (record.principalType !== 'user')
28
+ return 'not-a-user';
29
+ if (record.attributes.tenant !== tenant)
30
+ return 'wrong-tenant';
31
+ }
32
+ return undefined;
33
+ }
34
+ function isTrustedForwarder(forwarder) {
35
+ return (forwarder.authenticator === AUTHENTICATOR &&
36
+ forwarder.issuer === ISSUER &&
37
+ forwarder.principalType === 'service' &&
38
+ forwarder.attributes['jaccard:forwarder'] === 'true');
39
+ }
40
+ // The line carries ids only, never a token or an attribute.
41
+ function logRefusal(reason, forwarder, assertion) {
42
+ debugLine('Refused forwarded principal.', {
43
+ reason,
44
+ forwarder: forwarder.principalId,
45
+ principalId: assertion.principal?.current.principalId,
46
+ });
47
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Route auth for eve agents running on the Jaccard platform. The agent's
3
+ * channel file puts `jaccardOidc()` after `localDev()` in its chain:
4
+ * docs/eve-auth/overview.md.
5
+ */
6
+ export { jaccardOidc, type JaccardOidcOptions } from './oidc.js';
7
+ export { jaccardForwarders } from './forwarders.js';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Route auth for eve agents running on the Jaccard platform. The agent's
3
+ * channel file puts `jaccardOidc()` after `localDev()` in its chain:
4
+ * docs/eve-auth/overview.md.
5
+ */
6
+ export { jaccardOidc } from './oidc.js';
7
+ export { jaccardForwarders } from './forwarders.js';
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The Jaccard route authenticator: one entry of an eve authenticator chain
3
+ * that accepts a request carrying a valid identity token for this agent, and
4
+ * declines everything else (docs/eve-auth/18-jaccard-authenticator.md).
5
+ */
6
+ import type { AuthFn } from 'eve/channels/auth';
7
+ import type { JaccardOidcOptions } from './config.js';
8
+ export type { JaccardOidcOptions } from './config.js';
9
+ /**
10
+ * Returns the route authenticator. It resolves its settings on every request,
11
+ * so a missing one raises the setup refusal there. It reads `x-jaccard-identity`
12
+ * and never `authorization`.
13
+ */
14
+ export declare function jaccardOidc(options?: JaccardOidcOptions): AuthFn<Request>;
package/dist/oidc.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The Jaccard route authenticator: one entry of an eve authenticator chain
3
+ * that accepts a request carrying a valid identity token for this agent, and
4
+ * declines everything else (docs/eve-auth/18-jaccard-authenticator.md).
5
+ */
6
+ import { withAuthChallenges } from 'eve/channels/auth';
7
+ import { resolveSettings } from './config.js';
8
+ import { debugLine } from './diagnostics.js';
9
+ import { verifyIdentityToken } from './verify.js';
10
+ /**
11
+ * Returns the route authenticator. It resolves its settings on every request,
12
+ * so a missing one raises the setup refusal there. It reads `x-jaccard-identity`
13
+ * and never `authorization`.
14
+ */
15
+ export function jaccardOidc(options = {}) {
16
+ return withAuthChallenges(async (request) => {
17
+ const settings = resolveSettings(options);
18
+ const token = request.headers.get('x-jaccard-identity');
19
+ if (token === null)
20
+ return null;
21
+ const outcome = await verifyIdentityToken(token, settings);
22
+ if (!outcome.ok) {
23
+ debugLine('Rejected Jaccard identity token.', {
24
+ reason: outcome.reason,
25
+ subject: outcome.subject,
26
+ });
27
+ return null;
28
+ }
29
+ debugLine('Accepted Jaccard identity.', {
30
+ subject: outcome.subject,
31
+ principalType: outcome.record.principalType,
32
+ });
33
+ return outcome.record;
34
+ }, [{ scheme: 'Bearer' }]);
35
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The identity-token check (docs/eve-auth/18-jaccard-authenticator.md): a
3
+ * token is accepted only when the identity key set verifies it for this agent.
4
+ * `verifyIdentityToken` never throws for a bad token, and a rejection carries
5
+ * only a reason and the token's own `sub`, never the token.
6
+ */
7
+ import type { AuthResult } from 'eve/channels/auth';
8
+ import type { IdentitySettings } from './config.js';
9
+ export type VerifyFailure = 'malformed' | 'key-set-unavailable' | 'unknown-key' | 'invalid-signature' | 'wrong-issuer' | 'wrong-audience' | 'expired' | 'too-old' | 'invalid-identity';
10
+ /**
11
+ * The acceptance, with the tool-stub grant eve's channel reads at runtime. eve 1.0
12
+ * types the grant on `EveAuthResult` only, which eve 0.78 lacks; this compiles on both.
13
+ */
14
+ export type IdentityResult = AuthResult & {
15
+ readonly allowToolStubs?: boolean;
16
+ };
17
+ /** `subject` on a rejection is the token's `sub`, decoded without verification. */
18
+ export type VerifyOutcome = {
19
+ ok: true;
20
+ record: IdentityResult;
21
+ subject: string | undefined;
22
+ } | {
23
+ ok: false;
24
+ reason: VerifyFailure;
25
+ subject: string | undefined;
26
+ };
27
+ export declare function verifyIdentityToken(token: string, settings: IdentitySettings): Promise<VerifyOutcome>;
28
+ /** For tests only; index.ts must not re-export it. */
29
+ export declare function resetKeySets(fetchKeys?: typeof fetch): void;
package/dist/verify.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The identity-token check (docs/eve-auth/18-jaccard-authenticator.md): a
3
+ * token is accepted only when the identity key set verifies it for this agent.
4
+ * `verifyIdentityToken` never throws for a bad token, and a rejection carries
5
+ * only a reason and the token's own `sub`, never the token.
6
+ */
7
+ import { createRemoteJWKSet, customFetch, decodeJwt, errors, jwtVerify } from 'jose';
8
+ import { CLIENT_HEADER, clientHeader, installedEveVersion } from './client.js';
9
+ import { ISSUER } from './constants.js';
10
+ const ALGORITHM = 'ES256';
11
+ const CLOCK_TOLERANCE_SECONDS = 30;
12
+ const MAX_TOKEN_AGE_SECONDS = 90;
13
+ export async function verifyIdentityToken(token, settings) {
14
+ const audience = `tenant:${settings.tenant}:agent:${settings.agentName}`;
15
+ const unverified = decodeClaims(token);
16
+ if (!unverified)
17
+ return { ok: false, reason: 'malformed', subject: undefined };
18
+ const subject = text(unverified.sub);
19
+ let now = new Date();
20
+ try {
21
+ const keys = keySetAt(settings.identityJwksUrl);
22
+ // Load a missing or stale key set before the header is looked at, so a bad
23
+ // algorithm cannot hide an unreachable key set.
24
+ if (!keys.fresh)
25
+ await keys.reload();
26
+ now = new Date();
27
+ const { payload } = await jwtVerify(token, keys, {
28
+ algorithms: [ALGORITHM],
29
+ issuer: ISSUER,
30
+ audience,
31
+ maxTokenAge: MAX_TOKEN_AGE_SECONDS,
32
+ clockTolerance: CLOCK_TOLERANCE_SECONDS,
33
+ requiredClaims: ['exp', 'iat'],
34
+ // failureOf reads the same instant, or a boundary second could name the wrong claim.
35
+ currentDate: now,
36
+ });
37
+ const record = identityRecord(payload.jaccard_identity);
38
+ if (!record)
39
+ return { ok: false, reason: 'invalid-identity', subject: text(payload.sub) };
40
+ return {
41
+ ok: true,
42
+ record: payload.jaccard_tool_stubs === true ? { ...record, allowToolStubs: true } : record,
43
+ subject: text(payload.sub),
44
+ };
45
+ }
46
+ catch (error) {
47
+ return { ok: false, reason: failureOf(error, audience, now), subject };
48
+ }
49
+ }
50
+ function decodeClaims(token) {
51
+ try {
52
+ return decodeJwt(token);
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ const text = (value) => (typeof value === 'string' ? value : undefined);
59
+ // Checks the shape only: every caller passes parsed JSON, whose values are JSON too.
60
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
61
+ const isNonEmptyText = (value) => typeof value === 'string' && value !== '';
62
+ const isAttributeValue = (value) => typeof value === 'string' || (Array.isArray(value) && value.every((v) => typeof v === 'string'));
63
+ /**
64
+ * The record of spec 19 as the token carries it, or undefined when it does not
65
+ * fit the contract. Any grant field is dropped: the grant comes from the
66
+ * token's own claim and from nowhere else (spec 21).
67
+ */
68
+ function identityRecord(value) {
69
+ if (!isObject(value))
70
+ return undefined;
71
+ const { allowToolStubs: _grant, attributes, ...rest } = value;
72
+ if (!isNonEmptyText(rest.principalId))
73
+ return undefined;
74
+ if (!isNonEmptyText(rest.principalType))
75
+ return undefined;
76
+ if (!isNonEmptyText(rest.authenticator))
77
+ return undefined;
78
+ for (const optional of [rest.issuer, rest.subject]) {
79
+ if (optional !== undefined && !isNonEmptyText(optional))
80
+ return undefined;
81
+ }
82
+ if (!isObject(attributes) || !Object.values(attributes).every(isAttributeValue)) {
83
+ return undefined;
84
+ }
85
+ return { ...rest, attributes: Object.freeze({ ...attributes }) };
86
+ }
87
+ // The reason is the first failing claim in the order of spec 22, not jose's
88
+ // order: issuer, audience, exp, then iat.
89
+ function claimFailure(claims, audience, nowSeconds) {
90
+ if (claims.iss !== ISSUER)
91
+ return 'wrong-issuer';
92
+ const { aud } = claims;
93
+ if (!(typeof aud === 'string' ? aud === audience : Array.isArray(aud) && aud.includes(audience))) {
94
+ return 'wrong-audience';
95
+ }
96
+ const { exp, iat } = claims;
97
+ if (typeof exp !== 'number' || exp <= nowSeconds - CLOCK_TOLERANCE_SECONDS)
98
+ return 'expired';
99
+ if (typeof iat !== 'number' ||
100
+ iat > nowSeconds + CLOCK_TOLERANCE_SECONDS ||
101
+ nowSeconds - iat - CLOCK_TOLERANCE_SECONDS > MAX_TOKEN_AGE_SECONDS) {
102
+ return 'too-old';
103
+ }
104
+ return undefined;
105
+ }
106
+ // Every error that is not one of the named ones is a header or signature
107
+ // problem, including a key jose cannot use.
108
+ function failureOf(error, audience, now) {
109
+ if (error instanceof KeySetUnavailable)
110
+ return 'key-set-unavailable';
111
+ if (error instanceof errors.JWKSNoMatchingKey ||
112
+ error instanceof errors.JWKSMultipleMatchingKeys) {
113
+ return 'unknown-key';
114
+ }
115
+ if (error instanceof errors.JWTClaimValidationFailed || error instanceof errors.JWTExpired) {
116
+ return (claimFailure(error.payload, audience, Math.floor(now.getTime() / 1000)) ?? 'invalid-signature');
117
+ }
118
+ return 'invalid-signature';
119
+ }
120
+ class KeySetUnavailable extends Error {
121
+ }
122
+ const keySets = new Map();
123
+ const globalFetch = (input, init) => fetch(input, init);
124
+ let keySetFetch = globalFetch;
125
+ function keySetAt(jwksUrl) {
126
+ let keys = keySets.get(jwksUrl);
127
+ if (!keys) {
128
+ keys = createRemoteJWKSet(new URL(jwksUrl), {
129
+ cacheMaxAge: 600_000,
130
+ cooldownDuration: 30_000,
131
+ timeoutDuration: 5_000,
132
+ headers: { [CLIENT_HEADER]: clientHeader(installedEveVersion()) },
133
+ [customFetch]: fetchKeySet,
134
+ });
135
+ keySets.set(jwksUrl, keys);
136
+ }
137
+ return keys;
138
+ }
139
+ // Spec 12 behavior 9. Every failure here must become KeySetUnavailable, or it
140
+ // reads as invalid-signature.
141
+ const fetchKeySet = async (url, init) => {
142
+ try {
143
+ const response = await keySetFetch(url, init);
144
+ if (response.status !== 200 || !isKeySet(await response.clone().json())) {
145
+ throw new KeySetUnavailable();
146
+ }
147
+ return response;
148
+ }
149
+ catch {
150
+ throw new KeySetUnavailable();
151
+ }
152
+ };
153
+ const isKeySet = (body) => isObject(body) && Array.isArray(body.keys) && body.keys.every(isObject);
154
+ /** For tests only; index.ts must not re-export it. */
155
+ export function resetKeySets(fetchKeys = globalFetch) {
156
+ keySets.clear();
157
+ keySetFetch = fetchKeys;
158
+ }
package/package.json CHANGED
@@ -1 +1,52 @@
1
- {"name":"@jaccard-ai/eve-auth","version":"0.0.0","description":"Placeholder. Releases are published from CI.","license":"SEE LICENSE IN README.md"}
1
+ {
2
+ "name": "@jaccard-ai/eve-auth",
3
+ "version": "0.2.2-rc.1",
4
+ "description": "Route auth for eve agents on the Jaccard platform: verifies the identity token that the platform's auth service signs for each allowed request.",
5
+ "license": "SEE LICENSE IN README.md",
6
+ "homepage": "https://www.jaccard.ai",
7
+ "private": false,
8
+ "type": "module",
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./agents": {
17
+ "types": "./dist/agents.d.ts",
18
+ "default": "./dist/agents.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist/**/*.js",
23
+ "dist/**/*.d.ts",
24
+ "!dist/**/*.test.js",
25
+ "!dist/**/*.test.d.ts",
26
+ "README.md"
27
+ ],
28
+ "dependencies": {
29
+ "jose": "6.2.15"
30
+ },
31
+ "peerDependencies": {
32
+ "eve": ">=0.78.0 || >=1.0.0-rc.8"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.13.1",
36
+ "@vitest/coverage-v8": "^5.1.0",
37
+ "eve": "1.0.0-rc.8",
38
+ "typescript": "^7.0.2",
39
+ "vitest": "^5.1.0"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=24"
46
+ },
47
+ "scripts": {
48
+ "build": "tsc -p tsconfig.json",
49
+ "test": "vitest run",
50
+ "lint": "oxlint -c ../../../.oxlintrc.json && tsc -p tsconfig.json --noEmit && tsc -p examples/tsconfig.json"
51
+ }
52
+ }