@agentxgo/oauth 0.0.0-stage → 0.1.0-preview.2

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,114 @@
1
- # Temporary Holding Version
1
+ # AgentXGo OAuth SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Use AgentXGo's shared sign-in and per-connection MCP authorization in a Node.js
4
+ application. The SDK uses ESM and requires Node.js 22.12 or later.
5
+
6
+ ```sh
7
+ npm install @agentxgo/oauth@next
8
+ ```
9
+
10
+ Pin the version approved for your application. Supply your registered issuer,
11
+ client, callbacks, and resource identifiers from trusted application configuration.
12
+ Keep client and service credentials in your server's secret store.
13
+
14
+ ## Web sign-in and sign-out
15
+
16
+ Import `createWebOAuth` from `@agentxgo/oauth/web`. Pass the registered
17
+ `issuer`, `clientId`, `redirectUri`, and `postLogoutRedirectUri`.
18
+ Pass `clientSecret` for a confidential client registered for HTTP Basic
19
+ authentication. Provide a `transactions` store and a `recordLogout` handler.
20
+
21
+ 1. Call `beginLogin(returnTo)` with an application-relative path. Redirect the
22
+ browser to the returned `authorizationUrl`. Associate the returned `binding`
23
+ with that browser in a Secure, HttpOnly, SameSite=Lax cookie and expire it
24
+ with the transaction. Implement `save(binding, transaction)` on the server
25
+ and make `take(binding, state)` return and consume the matching unexpired
26
+ transaction in one operation.
27
+ 2. At the registered callback, call `completeLogin(callbackUrl, binding)`.
28
+ Match the verified `(issuer, subject)` to an existing, eligible local account.
29
+ Save the upstream `session` and `issuedAt` with the local session, clear the
30
+ browser binding, then redirect to the returned `returnTo`.
31
+ 3. Invalidate the local session before redirecting to `await web.logoutUrl()`.
32
+ At the registered back-channel callback, pass the `logout_token` form value to
33
+ `handleBackchannelLogout(token)`. In `recordLogout(event)`, atomically record
34
+ receipt by issuer, client, and event ID and revoke the matching local
35
+ sessions. Use the session ID when present and constrain it by subject when
36
+ supplied. A subject-only event applies to that subject's sessions for the
37
+ receiving application. Keep a receipt that prevents a concurrent callback
38
+ from recreating a session invalidated by the event. Return `true` when the
39
+ event is first applied and `false` on replay.
40
+
41
+ ### Verified email for first sign-in
42
+
43
+ Set `requestEmail: true` in `createWebOAuth` to request `openid email`.
44
+ Persist the complete login transaction, including its optional `emailRequested`
45
+ field. Configure the issuer to include `email` and `email_verified` in the
46
+ signed ID token. `completeLogin` exposes `identity.verifiedEmail` when the
47
+ original login requested it and the issuer reports `email_verified: true`
48
+ as a boolean with a usable address. The callback still returns a signed-in
49
+ identity when the address is unavailable.
50
+
51
+ Look up the account by `(issuer, subject)` first. For a new identity, apply
52
+ your application's provisioning rules and require the verified address if your
53
+ account model needs one. Route an address that belongs to an existing account
54
+ through your account-linking flow and verify control of that account. Use
55
+ `issuedAt` as the ID token's issue time. If your application records when it
56
+ observed email verification, record that time in the provisioning transaction.
57
+
58
+ ## MCP authorization
59
+
60
+ Import `createMcpOAuth` from `@agentxgo/oauth/mcp`. Pass your issuer,
61
+ exact resource HTTPS URL, registered clients, business scopes, and a
62
+ `hasGrant(binding)` handler.
63
+
64
+ - Serve `metadata` at `metadataUrl`. Use `challenge(requiredScopes)` for
65
+ the MCP endpoint's `WWW-Authenticate` header when it needs authorization.
66
+ Pass the operation's minimum business scopes. The challenge also requests
67
+ the sign-in and offline scopes used by the shared authorization server.
68
+ - Call `authorize(accessToken, requiredScopes)` before a protected operation.
69
+ Match the verified issuer, subject, client, resource, session, Grant, and
70
+ scopes against the original active Grant and the caller's current permissions
71
+ in `hasGrant`. The application owns its account, workspace, and resource
72
+ access checks.
73
+ - Handle `OAuthIntegrationError` by its `code` and `status`.
74
+ `invalid_token` is HTTP 401, `not_authorized` is HTTP 403, and
75
+ `unavailable` is HTTP 503.
76
+
77
+ Applications that own Grants can use `createGrantAuthority` from the same
78
+ entry point. Give it a dedicated service credential, the registered
79
+ issuer/resource/client tuples, and these application-owned callbacks.
80
+
81
+ | Callback | Application responsibility |
82
+ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `page` | Render the consent choices for the verified account and request. Escape displayed data and bind the consent proof to that request. |
84
+ | `approve` | Validate the proof, chosen target, membership, and scopes. Save a one-time authorization. Return an optional exact OAuth scope subset, or `null` on denial. |
85
+ | `attach` | Atomically redeem the original authorization and bind the Grant to the supplied session. Return the Grant reference, or `null` on denial. |
86
+ | `check` | Confirm the exact Grant binding and current access. The shared authorization server uses this check when refreshing a connection. |
87
+ | `revoke` | Revoke the matching Grant and handle retries for the same binding. |
88
+
89
+ ## Contract v1 and acceptance
90
+
91
+ The `@agentxgo/oauth/v1` entry point exports the manifest and evidence types
92
+ and the same checks used by the `agentxgo-oauth` command. Import
93
+ `@agentxgo/oauth/v1/example` with the JSON import attribute for a sample
94
+ manifest using example domains.
95
+
96
+ ```sh
97
+ npm exec -- agentxgo-oauth < profile.json
98
+ npm exec -- agentxgo-oauth --acceptance < evidence.json
99
+ ```
100
+
101
+ Record these observations from the application flows in redacted JSON.
102
+
103
+ - **Web** — Sign in through both applications using the same browser session.
104
+ Verify the original local account, workspace and requested page, then sign
105
+ out and check both applications and a separate session.
106
+ - **MCP** — Authorize connections A and B under the same person, SSO session,
107
+ client and resource. Verify distinct Grants and denied cross-resource access.
108
+ Revoke A, check that its calls and refresh fail, then refresh B and use it
109
+ again.
110
+
111
+ The command reports the result on success and identifies the failing contract
112
+ field on rejection.
113
+
114
+ Maintained by agentxgo team.
package/dist/bin.js ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process';
3
+ import { runNativeApplicationCli } from './contract.mjs';
4
+ process.exitCode = await runNativeApplicationCli();
@@ -0,0 +1,153 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import console from 'node:console';
3
+ import { resolve } from 'node:path';
4
+ import process from 'node:process';
5
+ import { fileURLToPath, URL } from 'node:url';
6
+ import { checkNativeAcceptance } from './native-application-acceptance.mjs';
7
+ export { checkNativeAcceptance };
8
+ function invalid(field) {
9
+ throw new Error(field);
10
+ }
11
+ function record(value, fields, field) {
12
+ if (!value ||
13
+ typeof value !== 'object' ||
14
+ Array.isArray(value) ||
15
+ fields.length !== Object.keys(value).length ||
16
+ fields.some((key) => !Object.hasOwn(value, key)))
17
+ invalid(field);
18
+ }
19
+ function list(value, field, callback, minimum = 1) {
20
+ if (!Array.isArray(value) || value.length < minimum || value.length > 256)
21
+ invalid(field);
22
+ value.forEach((item, index) => callback(item, `${field}[${index}]`));
23
+ }
24
+ function unique(values, value, field) {
25
+ if (values.has(value))
26
+ invalid(field);
27
+ values.add(value);
28
+ }
29
+ function identifier(value, field, pattern = /^[a-z][a-z0-9-]{0,62}$/) {
30
+ if (typeof value !== 'string' || !pattern.test(value))
31
+ invalid(field);
32
+ }
33
+ function https(value, field, mode = 'endpoint') {
34
+ const url = typeof value === 'string' && value.length <= 2048 ? URL.parse(value) : null;
35
+ if (!url ||
36
+ url.protocol !== 'https:' ||
37
+ url.username ||
38
+ url.password ||
39
+ value.includes('?') ||
40
+ value.includes('#') ||
41
+ value.includes('*') ||
42
+ /[%]2f|[%]5c/i.test(url.pathname) ||
43
+ (mode === 'origin'
44
+ ? url.origin !== value
45
+ : url.href !== value && !(mode === 'issuer' && url.origin === value)))
46
+ invalid(field);
47
+ return url;
48
+ }
49
+ function checkWeb(web, field, issuer, clients, webOrigins) {
50
+ record(web, [
51
+ 'issuer',
52
+ 'clientId',
53
+ 'origins',
54
+ 'redirectUris',
55
+ 'postLogoutRedirectUris',
56
+ 'backchannelLogoutUri',
57
+ ], field);
58
+ if (web.issuer !== issuer)
59
+ invalid(field + '.issuer');
60
+ identifier(web.clientId, field + '.clientId', /^[A-Za-z0-9._:-]{1,128}$/);
61
+ unique(clients, web.clientId, field + '.clientId');
62
+ const origins = new Set();
63
+ list(web.origins, field + '.origins', (origin, key) => {
64
+ https(origin, key, 'origin');
65
+ unique(webOrigins, origin, key);
66
+ origins.add(origin);
67
+ });
68
+ const checkCallback = (value, key) => {
69
+ if (!origins.has(https(value, key).origin))
70
+ invalid(key);
71
+ };
72
+ for (const kind of ['redirectUris', 'postLogoutRedirectUris']) {
73
+ const seen = new Set();
74
+ list(web[kind], field + '.' + kind, (value, key) => {
75
+ checkCallback(value, key);
76
+ unique(seen, value, key);
77
+ });
78
+ }
79
+ checkCallback(web.backchannelLogoutUri, field + '.backchannelLogoutUri');
80
+ }
81
+ function checkResource(mcp, field, issuer, resources) {
82
+ record(mcp, ['resource', 'audience', 'issuer', 'mode', 'scopes'], field);
83
+ https(mcp.resource, field + '.resource');
84
+ if (mcp.audience !== mcp.resource)
85
+ invalid(field + '.audience');
86
+ https(mcp.issuer, field + '.issuer', 'issuer');
87
+ if (mcp.mode !== 'legacy' && mcp.mode !== 'shared')
88
+ invalid(field + '.mode');
89
+ if (mcp.mode === 'shared' && mcp.issuer !== issuer)
90
+ invalid(field + '.issuer');
91
+ unique(resources, mcp.resource, field + '.resource');
92
+ const scopes = new Set();
93
+ list(mcp.scopes, field + '.scopes', (scope, key) => {
94
+ identifier(scope, key, /^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/);
95
+ unique(scopes, scope, key);
96
+ }, 0);
97
+ }
98
+ export function checkNativeApplications(profile) {
99
+ record(profile, ['schemaVersion', 'environment', 'identityIssuer', 'applications'], 'profile');
100
+ if (profile.schemaVersion !== 1)
101
+ invalid('schemaVersion');
102
+ identifier(profile.environment, 'environment');
103
+ https(profile.identityIssuer, 'identityIssuer', 'issuer');
104
+ const keys = new Set();
105
+ const clients = new Set();
106
+ const webOrigins = new Set();
107
+ const resources = new Set();
108
+ list(profile.applications, 'applications', (app, field) => {
109
+ record(app, ['key', 'web', 'mcp'], field);
110
+ identifier(app.key, field + '.key');
111
+ unique(keys, app.key, field + '.key');
112
+ checkWeb(app.web, field + '.web', profile.identityIssuer, clients, webOrigins);
113
+ list(app.mcp, field + '.mcp', (resource, key) => {
114
+ checkResource(resource, key, profile.identityIssuer, resources);
115
+ }, 0);
116
+ });
117
+ return { applications: keys.size, resources: resources.size };
118
+ }
119
+ async function readInput() {
120
+ const chunks = [];
121
+ let size = 0;
122
+ for await (const chunk of process.stdin) {
123
+ size += chunk.length;
124
+ if (size > 1024 * 1024)
125
+ invalid('inputSize');
126
+ chunks.push(chunk);
127
+ }
128
+ try {
129
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
130
+ }
131
+ catch {
132
+ invalid('json');
133
+ }
134
+ }
135
+ export async function runNativeApplicationCli(args = process.argv.slice(2)) {
136
+ try {
137
+ const [mode, ...rest] = args;
138
+ if (rest.length || (mode !== undefined && mode !== '--acceptance'))
139
+ invalid('arguments');
140
+ const input = await readInput();
141
+ const result = mode ? checkNativeAcceptance(input) : checkNativeApplications(input);
142
+ console.log(JSON.stringify({ ok: true, ...result }));
143
+ return 0;
144
+ }
145
+ catch (error) {
146
+ const field = error instanceof Error && /^[A-Za-z0-9.[\]]+$/.test(error.message) ? error.message : 'input';
147
+ console.error(JSON.stringify({ ok: false, field }));
148
+ return 1;
149
+ }
150
+ }
151
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
152
+ process.exitCode = await runNativeApplicationCli();
153
+ }
@@ -0,0 +1,16 @@
1
+ declare const failures: {
2
+ readonly invalid_configuration: readonly [500, "OAuth integration configuration is invalid."];
3
+ readonly invalid_login: readonly [401, "The sign-in response could not be verified."];
4
+ readonly invalid_logout: readonly [400, "The sign-out notification could not be accepted."];
5
+ readonly invalid_token: readonly [401, "A valid access token is required."];
6
+ readonly not_authorized: readonly [403, "The requested operation is not authorized."];
7
+ readonly unavailable: readonly [503, "OAuth integration is temporarily unavailable."];
8
+ };
9
+ export type OAuthIntegrationErrorCode = keyof typeof failures;
10
+ export declare class OAuthIntegrationError extends Error {
11
+ readonly code: OAuthIntegrationErrorCode;
12
+ readonly name = "OAuthIntegrationError";
13
+ readonly status: (typeof failures)[OAuthIntegrationErrorCode][0];
14
+ constructor(code: OAuthIntegrationErrorCode);
15
+ }
16
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,18 @@
1
+ const failures = {
2
+ invalid_configuration: [500, 'OAuth integration configuration is invalid.'],
3
+ invalid_login: [401, 'The sign-in response could not be verified.'],
4
+ invalid_logout: [400, 'The sign-out notification could not be accepted.'],
5
+ invalid_token: [401, 'A valid access token is required.'],
6
+ not_authorized: [403, 'The requested operation is not authorized.'],
7
+ unavailable: [503, 'OAuth integration is temporarily unavailable.'],
8
+ };
9
+ export class OAuthIntegrationError extends Error {
10
+ code;
11
+ name = 'OAuthIntegrationError';
12
+ status;
13
+ constructor(code) {
14
+ super(failures[code][1]);
15
+ this.code = code;
16
+ this.status = failures[code][0];
17
+ }
18
+ }
@@ -0,0 +1,47 @@
1
+ import type { Awaitable } from './types.js';
2
+ export interface GrantRoute {
3
+ readonly issuer: string;
4
+ readonly resource: string;
5
+ readonly client: string;
6
+ }
7
+ interface GrantRequest extends GrantRoute {
8
+ readonly subject: string;
9
+ readonly scopes: readonly string[];
10
+ }
11
+ interface ConsentRequest extends GrantRequest {
12
+ readonly challenge: string;
13
+ readonly tab: string;
14
+ readonly redirectUri: string;
15
+ readonly purpose?: string;
16
+ }
17
+ export interface GrantPageRequest extends ConsentRequest {
18
+ readonly formAction: string;
19
+ readonly clientName: string;
20
+ }
21
+ export interface GrantApprovalRequest extends ConsentRequest {
22
+ readonly proof: string;
23
+ readonly target: string;
24
+ readonly grantedScopes?: readonly string[];
25
+ }
26
+ export interface GrantApproval {
27
+ readonly scope?: readonly string[];
28
+ }
29
+ export interface GrantAttachRequest extends GrantRequest {
30
+ readonly challenge: string;
31
+ readonly session: string;
32
+ }
33
+ export interface GrantBindingRequest extends GrantRequest {
34
+ readonly grant: string;
35
+ readonly session: string;
36
+ }
37
+ export interface GrantAuthorityOptions {
38
+ credential: string;
39
+ routes: readonly GrantRoute[];
40
+ page: (input: GrantPageRequest) => Awaitable<string | null>;
41
+ approve: (input: GrantApprovalRequest) => Awaitable<GrantApproval | null>;
42
+ attach: (input: GrantAttachRequest) => Awaitable<string | null>;
43
+ check: (input: GrantBindingRequest) => Awaitable<boolean>;
44
+ revoke: (input: GrantBindingRequest) => Awaitable<boolean>;
45
+ }
46
+ export declare function createGrantAuthority(options: GrantAuthorityOptions): (request: Request) => Promise<Response>;
47
+ export {};
@@ -0,0 +1,196 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { createHash, timingSafeEqual } from 'node:crypto';
3
+ import { OAuthIntegrationError } from './errors.js';
4
+ import { clientIdentifier, exactText, https } from './issuer.js';
5
+ import { grantReference, isBusinessScope, parseConnectionScopes, parseScopes } from './scopes.js';
6
+ const challengePattern = /^[A-Za-z0-9_-]{43}$/;
7
+ const maximumFormBytes = 32768;
8
+ const routeKey = (...parts) => JSON.stringify(parts);
9
+ const digest = (value) => createHash('sha256').update(value).digest();
10
+ const consentFields = ['challenge', 'tab', 'redirect_uri', 'purpose'];
11
+ const commonFields = ['action', 'issuer', 'resource', 'client', 'subject', 'scope'];
12
+ const actionFields = {
13
+ page: [...consentFields, 'form_action', 'client_name'],
14
+ approve: [...consentFields, 'proof', 'target', 'granted_scope'],
15
+ attach: ['challenge', 'session'],
16
+ check: ['session', 'grant'],
17
+ revoke: ['session', 'grant'],
18
+ };
19
+ async function readForm(request) {
20
+ if (!request.body)
21
+ return null;
22
+ const reader = request.body.getReader();
23
+ let size = 0;
24
+ const decoder = new TextDecoder('utf-8', { fatal: true });
25
+ const parts = [];
26
+ try {
27
+ while (true) {
28
+ const { done, value } = await reader.read();
29
+ if (done)
30
+ break;
31
+ size += value.byteLength;
32
+ if (size > maximumFormBytes) {
33
+ void reader.cancel().catch(() => { });
34
+ return null;
35
+ }
36
+ parts.push(decoder.decode(value, { stream: true }));
37
+ }
38
+ const form = new URLSearchParams(parts.join('') + decoder.decode());
39
+ return new Set(form.keys()).size === form.size ? form : null;
40
+ }
41
+ catch {
42
+ void reader.cancel().catch(() => { });
43
+ return null;
44
+ }
45
+ finally {
46
+ reader.releaseLock();
47
+ }
48
+ }
49
+ function answer(status, body = null, contentType = 'text/plain') {
50
+ const headers = new Headers({ 'cache-control': 'no-store' });
51
+ if (body !== null)
52
+ headers.set('content-type', contentType + '; charset=utf-8');
53
+ if (contentType === 'text/html') {
54
+ headers.set('referrer-policy', 'no-referrer');
55
+ headers.set('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
56
+ }
57
+ return new Response(body, { status, headers });
58
+ }
59
+ function validClientRedirect(value) {
60
+ if (!exactText(value, 2048) || value.includes('#'))
61
+ return false;
62
+ const url = URL.parse(value);
63
+ return Boolean(url &&
64
+ !url.username &&
65
+ !url.password &&
66
+ (url.protocol === 'https:' ||
67
+ (url.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname)) ||
68
+ (/^[a-z][a-z\d+-]*(?:\.[a-z\d+-]+)+:$/.test(url.protocol) &&
69
+ value.startsWith(url.protocol + '/'))));
70
+ }
71
+ export function createGrantAuthority(options) {
72
+ if (!exactText(options.credential, 4096) ||
73
+ /\s/.test(options.credential) ||
74
+ !Array.isArray(options.routes) ||
75
+ !options.routes.length ||
76
+ options.routes.length > 256 ||
77
+ !options.routes.every((route) => route &&
78
+ https(route.issuer, 'issuer') &&
79
+ https(route.resource) &&
80
+ clientIdentifier(route.client)) ||
81
+ [options.page, options.approve, options.attach, options.check, options.revoke].some((callback) => typeof callback !== 'function'))
82
+ throw new OAuthIntegrationError('invalid_configuration');
83
+ const routes = new Set(options.routes.map(({ issuer, resource, client }) => routeKey(issuer, resource, client)));
84
+ if (routes.size !== options.routes.length)
85
+ throw new OAuthIntegrationError('invalid_configuration');
86
+ const caller = digest('Bearer ' + options.credential);
87
+ return async (request) => {
88
+ const authorization = request.headers.get('authorization');
89
+ if (!exactText(authorization, 4103) || !timingSafeEqual(digest(authorization), caller))
90
+ return answer(401);
91
+ if (request.method !== 'POST' ||
92
+ !https(request.url) ||
93
+ !/^application\/x-www-form-urlencoded(?:\s*;|$)/i.test(request.headers.get('content-type') ?? ''))
94
+ return answer(400);
95
+ const form = await readForm(request);
96
+ if (!form)
97
+ return answer(400);
98
+ const action = form.get('action');
99
+ if (!action || !Object.hasOwn(actionFields, action))
100
+ return answer(403);
101
+ const accepted = [...commonFields, ...actionFields[action]];
102
+ if ([...form.keys()].some((key) => !accepted.includes(key)))
103
+ return answer(403);
104
+ const issuer = form.get('issuer');
105
+ const client = form.get('client');
106
+ const resource = form.get('resource');
107
+ const subject = form.get('subject');
108
+ const scopes = parseConnectionScopes(form.get('scope'));
109
+ if (!exactText(issuer, 2048) ||
110
+ !exactText(resource, 2048) ||
111
+ !clientIdentifier(client) ||
112
+ !routes.has(routeKey(issuer, resource, client)) ||
113
+ !exactText(subject) ||
114
+ !scopes)
115
+ return answer(403);
116
+ const input = { issuer, client, resource, subject, scopes: Object.freeze(scopes) };
117
+ try {
118
+ if (action === 'page' || action === 'approve') {
119
+ const challenge = form.get('challenge');
120
+ const tab = form.get('tab');
121
+ const redirectUri = form.get('redirect_uri');
122
+ const purpose = form.get('purpose');
123
+ if (!challenge ||
124
+ !challengePattern.test(challenge) ||
125
+ !exactText(tab, 200) ||
126
+ !validClientRedirect(redirectUri) ||
127
+ (purpose !== null && !exactText(purpose, 128)))
128
+ return answer(403);
129
+ const consent = {
130
+ ...input,
131
+ challenge,
132
+ tab,
133
+ redirectUri,
134
+ ...(purpose === null ? {} : { purpose }),
135
+ };
136
+ if (action === 'page') {
137
+ const formAction = https(form.get('form_action'), 'endpoint');
138
+ const clientName = form.get('client_name');
139
+ if (!formAction ||
140
+ formAction.origin !== new URL(issuer).origin ||
141
+ !exactText(clientName, 200))
142
+ return answer(403);
143
+ const page = await options.page({ ...consent, formAction: formAction.href, clientName });
144
+ if (page === null)
145
+ return answer(403);
146
+ if (typeof page !== 'string' || !page.length || Buffer.byteLength(page) > 1024 * 1024)
147
+ return answer(503);
148
+ return answer(200, page, 'text/html');
149
+ }
150
+ const proof = form.get('proof');
151
+ const target = form.get('target');
152
+ const selection = form.get('granted_scope');
153
+ const selected = selection === null ? null : parseScopes(selection);
154
+ if (!exactText(proof, 4096) ||
155
+ !exactText(target) ||
156
+ (selection !== null && (!selected || selected.some((scope) => !scopes.includes(scope)))))
157
+ return answer(403);
158
+ const approved = await options.approve({
159
+ ...consent,
160
+ proof,
161
+ target,
162
+ ...(selected ? { grantedScopes: Object.freeze(selected) } : {}),
163
+ });
164
+ if (!approved)
165
+ return answer(403);
166
+ const effective = approved.scope === undefined ? scopes : parseConnectionScopes(approved.scope.join(' '));
167
+ if (!effective ||
168
+ effective.some((scope) => !scopes.includes(scope)) ||
169
+ (selected && effective.filter(isBusinessScope).some((scope) => !selected.includes(scope))))
170
+ return answer(403);
171
+ return approved.scope === undefined ? answer(204) : answer(200, effective.join(' '));
172
+ }
173
+ const session = form.get('session');
174
+ if (!exactText(session, 128))
175
+ return answer(403);
176
+ if (action === 'attach') {
177
+ const challenge = form.get('challenge');
178
+ if (!challenge || !challengePattern.test(challenge))
179
+ return answer(403);
180
+ const grant = await options.attach({ ...input, session, challenge });
181
+ if (grant === null)
182
+ return answer(403);
183
+ return grantReference.test(grant) ? answer(200, grant) : answer(503);
184
+ }
185
+ const grant = form.get('grant');
186
+ if (!grant || !grantReference.test(grant))
187
+ return answer(403);
188
+ const binding = { ...input, session, grant };
189
+ const allowed = action === 'check' ? await options.check(binding) : await options.revoke(binding);
190
+ return answer(allowed === true ? 204 : 403);
191
+ }
192
+ catch {
193
+ return answer(503);
194
+ }
195
+ };
196
+ }
@@ -0,0 +1,3 @@
1
+ export * from './web.js';
2
+ export * from './mcp.js';
3
+ export * from './v1.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './web.js';
2
+ export * from './mcp.js';
3
+ export * from './v1.js';
package/dist/issuer.js ADDED
@@ -0,0 +1,108 @@
1
+ import { createRemoteJWKSet, customFetch, errors } from 'jose';
2
+ import * as oidc from 'openid-client';
3
+ import { OAuthIntegrationError } from './errors.js';
4
+ export function exactText(value, max = 512) {
5
+ return (typeof value === 'string' &&
6
+ value.length > 0 &&
7
+ value.length <= max &&
8
+ value.trim() === value &&
9
+ !/\p{Cc}/u.test(value));
10
+ }
11
+ export function clientIdentifier(value) {
12
+ return typeof value === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(value);
13
+ }
14
+ export function https(value, mode = 'exact') {
15
+ if (!exactText(value, mode === 'endpoint' ? 8192 : 2048) || value.includes('#'))
16
+ return null;
17
+ const url = URL.parse(value);
18
+ if (!url ||
19
+ url.protocol !== 'https:' ||
20
+ url.username ||
21
+ url.password ||
22
+ /\\|%2f|%5c/i.test(url.pathname) ||
23
+ (mode !== 'endpoint' && (value.includes('?') || value.includes('*'))) ||
24
+ (url.href !== value && !(mode === 'issuer' && url.origin === value)))
25
+ return null;
26
+ return url;
27
+ }
28
+ export function epoch(value) {
29
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
30
+ }
31
+ export const nowSeconds = () => Math.floor(Date.now() / 1000);
32
+ export function issuerAccess(options, client) {
33
+ const { issuer } = options;
34
+ const configured = https(issuer, 'issuer');
35
+ if (!configured)
36
+ throw new OAuthIntegrationError('invalid_configuration');
37
+ const transport = options.fetch ?? globalThis.fetch;
38
+ const endpoint = (value) => {
39
+ const url = https(value, 'endpoint');
40
+ if (!url || url.origin !== configured.origin)
41
+ throw new OAuthIntegrationError('unavailable');
42
+ return url;
43
+ };
44
+ const guardedFetch = async (target, init) => {
45
+ try {
46
+ endpoint(target instanceof Request ? target.url : String(target));
47
+ const response = await transport(target, { ...init, redirect: 'error' });
48
+ if (!response.redirected && response.status < 500 && response.status !== 429)
49
+ return response;
50
+ await response.body?.cancel().catch(() => { });
51
+ }
52
+ catch {
53
+ throw new OAuthIntegrationError('unavailable');
54
+ }
55
+ throw new OAuthIntegrationError('unavailable');
56
+ };
57
+ const discover = async () => {
58
+ const discovery = new URL(issuer.replace(/\/$/, '') + '/.well-known/openid-configuration');
59
+ const config = await oidc.discovery(discovery, client?.id ?? 'resource-discovery', { id_token_signed_response_alg: 'RS256' }, client?.secret === undefined ? oidc.None() : oidc.ClientSecretBasic(client.secret), {
60
+ timeout: 5,
61
+ execute: client ? [oidc.enableNonRepudiationChecks] : [],
62
+ [oidc.customFetch]: (target, { body, ...init }) => body === undefined
63
+ ? guardedFetch(target, init)
64
+ : guardedFetch(target, {
65
+ ...init,
66
+ body: body instanceof Uint8Array ? Uint8Array.from(body) : body,
67
+ }),
68
+ });
69
+ const metadata = config.serverMetadata();
70
+ if (metadata.issuer !== issuer)
71
+ throw new OAuthIntegrationError('unavailable');
72
+ const jwks = endpoint(metadata.jwks_uri);
73
+ if (client) {
74
+ endpoint(metadata.authorization_endpoint);
75
+ endpoint(metadata.token_endpoint);
76
+ if (metadata.end_session_endpoint)
77
+ endpoint(metadata.end_session_endpoint);
78
+ if (!metadata.supportsPKCE('S256'))
79
+ throw new OAuthIntegrationError('unavailable');
80
+ }
81
+ const keys = createRemoteJWKSet(jwks, {
82
+ timeoutDuration: 5000,
83
+ [customFetch]: async (url, init) => {
84
+ const response = await guardedFetch(url, init);
85
+ if (!response.ok) {
86
+ await response.body?.cancel().catch(() => { });
87
+ throw new OAuthIntegrationError('unavailable');
88
+ }
89
+ return response;
90
+ },
91
+ });
92
+ return { config, keys };
93
+ };
94
+ let discovered;
95
+ return () => (discovered ??= discover().catch(() => {
96
+ discovered = undefined;
97
+ throw new OAuthIntegrationError('unavailable');
98
+ }));
99
+ }
100
+ export function protocolFailure(error, fallback) {
101
+ if ((error instanceof OAuthIntegrationError && error.code === 'unavailable') ||
102
+ error instanceof errors.JWKSTimeout ||
103
+ (error instanceof oidc.ClientError &&
104
+ (error.code === 'OAUTH_TIMEOUT' ||
105
+ (error.cause instanceof OAuthIntegrationError && error.cause.code === 'unavailable'))))
106
+ return new OAuthIntegrationError('unavailable');
107
+ return new OAuthIntegrationError(fallback);
108
+ }
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { Awaitable } from './types.js';
2
+ export { createGrantAuthority } from './grant-authority.js';
3
+ export type { GrantApproval, GrantApprovalRequest, GrantAttachRequest, GrantAuthorityOptions, GrantBindingRequest, GrantPageRequest, GrantRoute, } from './grant-authority.js';
4
+ export { OAuthIntegrationError, type OAuthIntegrationErrorCode } from './errors.js';
5
+ export interface McpGrantBinding {
6
+ readonly issuer: string;
7
+ readonly subject: string;
8
+ readonly client: string;
9
+ readonly resource: string;
10
+ readonly session: string;
11
+ readonly grant: string;
12
+ readonly scopes: readonly string[];
13
+ readonly issuedAt: number;
14
+ readonly expiresAt: number;
15
+ }
16
+ export interface McpOAuthOptions {
17
+ issuer: string;
18
+ resource: string;
19
+ clients: readonly string[];
20
+ scopes: readonly string[];
21
+ hasGrant(binding: McpGrantBinding): Awaitable<boolean>;
22
+ fetch?: typeof fetch;
23
+ }
24
+ export interface McpResourceMetadata {
25
+ readonly resource: string;
26
+ readonly authorization_servers: readonly string[];
27
+ readonly scopes_supported: readonly string[];
28
+ readonly bearer_methods_supported: readonly ['header'];
29
+ }
30
+ export interface McpOAuth {
31
+ readonly metadata: McpResourceMetadata;
32
+ readonly metadataUrl: string;
33
+ challenge(requiredScopes: readonly string[], error?: 'invalid_token' | 'insufficient_scope'): string;
34
+ authorize(token: string, requiredScopes?: readonly string[]): Promise<McpGrantBinding>;
35
+ }
36
+ export declare function createMcpOAuth(options: McpOAuthOptions): McpOAuth;
package/dist/mcp.js ADDED
@@ -0,0 +1,100 @@
1
+ import { jwtVerify } from 'jose';
2
+ import { OAuthIntegrationError } from './errors.js';
3
+ import { clientIdentifier, epoch, exactText, https, issuerAccess, nowSeconds, protocolFailure, } from './issuer.js';
4
+ import { grantReference, isBusinessScope, parseConnectionScopes } from './scopes.js';
5
+ export { createGrantAuthority } from './grant-authority.js';
6
+ export { OAuthIntegrationError } from './errors.js';
7
+ export function createMcpOAuth(options) {
8
+ const { issuer, resource } = options;
9
+ const resourceUrl = https(resource);
10
+ if (!resourceUrl ||
11
+ !Array.isArray(options.clients) ||
12
+ !options.clients.length ||
13
+ !options.clients.every(clientIdentifier) ||
14
+ !Array.isArray(options.scopes) ||
15
+ !options.scopes.length ||
16
+ !options.scopes.every(isBusinessScope) ||
17
+ typeof options.hasGrant !== 'function')
18
+ throw new OAuthIntegrationError('invalid_configuration');
19
+ const clients = new Set(options.clients);
20
+ const offered = Object.freeze([...new Set(options.scopes)]);
21
+ const discovery = issuerAccess(options);
22
+ const metadataUrl = resourceUrl.origin +
23
+ '/.well-known/oauth-protected-resource' +
24
+ (resourceUrl.pathname === '/' ? '' : resourceUrl.pathname);
25
+ const metadata = Object.freeze({
26
+ resource,
27
+ authorization_servers: Object.freeze([issuer]),
28
+ scopes_supported: offered,
29
+ bearer_methods_supported: Object.freeze(['header']),
30
+ });
31
+ return {
32
+ metadata,
33
+ metadataUrl,
34
+ challenge(requiredScopes, error) {
35
+ if (!requiredScopes.length ||
36
+ requiredScopes.some((scope) => !offered.includes(scope)) ||
37
+ (error !== undefined && error !== 'invalid_token' && error !== 'insufficient_scope'))
38
+ throw new OAuthIntegrationError('invalid_configuration');
39
+ const scope = ['openid', 'offline_access', ...new Set(requiredScopes)].join(' ');
40
+ const fields = ['resource_metadata="' + metadataUrl + '"', 'scope="' + scope + '"'];
41
+ if (error !== undefined)
42
+ fields.push('error="' + error + '"');
43
+ return 'Bearer ' + fields.join(', ');
44
+ },
45
+ async authorize(token, requiredScopes = []) {
46
+ if (!exactText(token, 8192))
47
+ throw new OAuthIntegrationError('invalid_token');
48
+ const { keys } = await discovery();
49
+ const { payload } = await jwtVerify(token, keys, {
50
+ issuer,
51
+ audience: resource,
52
+ algorithms: ['RS256'],
53
+ requiredClaims: ['sub', 'sid', 'azp', 'jti', 'typ', 'iat', 'exp'],
54
+ }).catch((error) => {
55
+ throw protocolFailure(error, 'invalid_token');
56
+ });
57
+ const { typ, sub, sid, azp, aud, jti, iat, exp, agentxgo_grant_id: grant } = payload;
58
+ const scopes = parseConnectionScopes(payload.scope)?.filter(isBusinessScope);
59
+ if (typ !== 'Bearer' ||
60
+ !clientIdentifier(azp) ||
61
+ !clients.has(azp) ||
62
+ (Array.isArray(aud) ? aud.length !== 1 || aud[0] !== resource : aud !== resource) ||
63
+ !exactText(sub) ||
64
+ !exactText(sid, 128) ||
65
+ !exactText(jti, 128) ||
66
+ !epoch(iat) ||
67
+ !epoch(exp) ||
68
+ iat > nowSeconds() + 30 ||
69
+ exp <= iat ||
70
+ typeof grant !== 'string' ||
71
+ !grantReference.test(grant) ||
72
+ !scopes ||
73
+ scopes.some((scope) => !offered.includes(scope)))
74
+ throw new OAuthIntegrationError('invalid_token');
75
+ const binding = Object.freeze({
76
+ issuer,
77
+ subject: sub,
78
+ client: azp,
79
+ resource,
80
+ session: sid,
81
+ grant,
82
+ scopes: Object.freeze(scopes),
83
+ issuedAt: iat,
84
+ expiresAt: exp,
85
+ });
86
+ let active;
87
+ try {
88
+ active = await options.hasGrant(binding);
89
+ }
90
+ catch {
91
+ throw new OAuthIntegrationError('unavailable');
92
+ }
93
+ if (active !== true)
94
+ throw new OAuthIntegrationError('invalid_token');
95
+ if (requiredScopes.some((scope) => !scopes.includes(scope)))
96
+ throw new OAuthIntegrationError('not_authorized');
97
+ return binding;
98
+ },
99
+ };
100
+ }
@@ -0,0 +1,46 @@
1
+ export function checkNativeAcceptance(evidence) {
2
+ if (evidence?.schemaVersion !== 1)
3
+ throw new Error('schemaVersion');
4
+ const expect = (field, value) => {
5
+ const actual = evidence[field];
6
+ const matches = Array.isArray(value)
7
+ ? Array.isArray(actual) &&
8
+ value.length === actual.length &&
9
+ value.every((item, i) => item === actual[i])
10
+ : actual === value;
11
+ if (!matches)
12
+ throw new Error(field);
13
+ };
14
+ if (evidence.flow === 'web') {
15
+ for (const field of [
16
+ 'ssoWithoutSecondPrompt',
17
+ 'reverseEntryWithoutPrompt',
18
+ 'originalPrincipal',
19
+ 'originalWorkspace',
20
+ 'deepLinkRestored',
21
+ 'boundAccountRequired',
22
+ ])
23
+ expect(field, true);
24
+ expect('beforeLogout', [200, 200]);
25
+ expect('afterLogout', [401, 401]);
26
+ expect('unrelatedSession', [200, 200]);
27
+ }
28
+ else if (evidence.flow === 'mcp') {
29
+ for (const field of [
30
+ 'sameSubjectClientSessionAndResource',
31
+ 'distinctGrants',
32
+ 'originalContext',
33
+ 'crossResourceDenied',
34
+ ])
35
+ expect(field, true);
36
+ expect('beforeRevoke', [200, 200]);
37
+ expect('afterRevoke', [401, 200]);
38
+ expect('refreshAfterRevoke', [400, 200]);
39
+ expect('revokedRefreshError', 'invalid_grant');
40
+ expect('survivingAccess', 200);
41
+ }
42
+ else {
43
+ throw new Error('flow');
44
+ }
45
+ return { flow: evidence.flow };
46
+ }
@@ -0,0 +1,39 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "environment": "development",
4
+ "identityIssuer": "https://identity.example.test",
5
+ "applications": [
6
+ {
7
+ "key": "workspace",
8
+ "web": {
9
+ "issuer": "https://identity.example.test",
10
+ "clientId": "workspace-web",
11
+ "origins": ["https://workspace.example.test"],
12
+ "redirectUris": ["https://workspace.example.test/sign-in/complete"],
13
+ "postLogoutRedirectUris": ["https://workspace.example.test/signed-out"],
14
+ "backchannelLogoutUri": "https://workspace.example.test/sign-out/notify"
15
+ },
16
+ "mcp": []
17
+ },
18
+ {
19
+ "key": "creative-app",
20
+ "web": {
21
+ "issuer": "https://identity.example.test",
22
+ "clientId": "creative-app-web",
23
+ "origins": ["https://creative-app.example.test"],
24
+ "redirectUris": ["https://creative-app.example.test/sign-in/complete"],
25
+ "postLogoutRedirectUris": ["https://creative-app.example.test/signed-out"],
26
+ "backchannelLogoutUri": "https://creative-app.example.test/sign-out/notify"
27
+ },
28
+ "mcp": [
29
+ {
30
+ "resource": "https://creative-app.example.test/mcp",
31
+ "audience": "https://creative-app.example.test/mcp",
32
+ "issuer": "https://identity.example.test",
33
+ "mode": "shared",
34
+ "scopes": ["content:read"]
35
+ }
36
+ ]
37
+ }
38
+ ]
39
+ }
package/dist/scopes.js ADDED
@@ -0,0 +1,20 @@
1
+ export const grantReference = /^(?:tgrant_)?[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
2
+ const scopeToken = /^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/;
3
+ const protocolScopes = new Set(['openid', 'offline_access', 'basic']);
4
+ export const isBusinessScope = (scope) => typeof scope === 'string' && scopeToken.test(scope) && !protocolScopes.has(scope);
5
+ export function parseScopes(value) {
6
+ if (typeof value !== 'string' || value.length === 0 || value.length > 4096)
7
+ return null;
8
+ const scopes = value.split(/ +/);
9
+ if (scopes.some((scope) => !scopeToken.test(scope)) || new Set(scopes).size !== scopes.length)
10
+ return null;
11
+ return scopes;
12
+ }
13
+ export function parseConnectionScopes(value) {
14
+ const scopes = parseScopes(value);
15
+ return scopes?.includes('openid') &&
16
+ scopes.includes('offline_access') &&
17
+ scopes.some(isBusinessScope)
18
+ ? scopes
19
+ : null;
20
+ }
@@ -0,0 +1 @@
1
+ export type Awaitable<T> = T | Promise<T>;
package/dist/v1.d.ts ADDED
@@ -0,0 +1,58 @@
1
+ export interface NativeApplicationProfile {
2
+ readonly schemaVersion: 1;
3
+ readonly environment: string;
4
+ readonly identityIssuer: string;
5
+ readonly applications: readonly NativeApplication[];
6
+ }
7
+ export interface NativeApplication {
8
+ readonly key: string;
9
+ readonly web: {
10
+ readonly issuer: string;
11
+ readonly clientId: string;
12
+ readonly origins: readonly string[];
13
+ readonly redirectUris: readonly string[];
14
+ readonly postLogoutRedirectUris: readonly string[];
15
+ readonly backchannelLogoutUri: string;
16
+ };
17
+ readonly mcp: readonly {
18
+ readonly resource: string;
19
+ readonly audience: string;
20
+ readonly issuer: string;
21
+ readonly mode: 'legacy' | 'shared';
22
+ readonly scopes: readonly string[];
23
+ }[];
24
+ }
25
+ export interface WebAcceptanceEvidence {
26
+ readonly schemaVersion: 1;
27
+ readonly flow: 'web';
28
+ readonly ssoWithoutSecondPrompt: boolean;
29
+ readonly reverseEntryWithoutPrompt: boolean;
30
+ readonly originalPrincipal: boolean;
31
+ readonly originalWorkspace: boolean;
32
+ readonly deepLinkRestored: boolean;
33
+ readonly boundAccountRequired: boolean;
34
+ readonly beforeLogout: readonly [number, number];
35
+ readonly afterLogout: readonly [number, number];
36
+ readonly unrelatedSession: readonly [number, number];
37
+ }
38
+ export interface McpAcceptanceEvidence {
39
+ readonly schemaVersion: 1;
40
+ readonly flow: 'mcp';
41
+ readonly sameSubjectClientSessionAndResource: boolean;
42
+ readonly distinctGrants: boolean;
43
+ readonly originalContext: boolean;
44
+ readonly crossResourceDenied: boolean;
45
+ readonly beforeRevoke: readonly [number, number];
46
+ readonly afterRevoke: readonly [number, number];
47
+ readonly refreshAfterRevoke: readonly [number, number];
48
+ readonly revokedRefreshError: string;
49
+ readonly survivingAccess: number;
50
+ }
51
+ export type NativeAcceptanceEvidence = WebAcceptanceEvidence | McpAcceptanceEvidence;
52
+ export declare function checkNativeApplications(profile: unknown): {
53
+ applications: number;
54
+ resources: number;
55
+ };
56
+ export declare function checkNativeAcceptance(evidence: unknown): {
57
+ flow: 'web' | 'mcp';
58
+ };
package/dist/v1.js ADDED
@@ -0,0 +1 @@
1
+ export { checkNativeApplications, checkNativeAcceptance } from './contract.mjs';
package/dist/web.d.ts ADDED
@@ -0,0 +1,56 @@
1
+ import type { Awaitable } from './types.js';
2
+ export interface WebLoginTransaction {
3
+ readonly issuer: string;
4
+ readonly clientId: string;
5
+ readonly redirectUri: string;
6
+ readonly state: string;
7
+ readonly nonce: string;
8
+ readonly verifier: string;
9
+ readonly returnTo: string;
10
+ readonly expiresAt: number;
11
+ readonly emailRequested?: true;
12
+ }
13
+ export interface WebLoginStore {
14
+ save(binding: string, transaction: WebLoginTransaction): Awaitable<void>;
15
+ take(binding: string, state: string): Awaitable<WebLoginTransaction | null>;
16
+ }
17
+ export interface WebIdentity {
18
+ readonly issuer: string;
19
+ readonly subject: string;
20
+ readonly session: string;
21
+ readonly issuedAt: number;
22
+ readonly verifiedEmail?: string;
23
+ }
24
+ export interface WebLogoutEvent {
25
+ readonly issuer: string;
26
+ readonly clientId: string;
27
+ readonly id: string;
28
+ readonly issuedAt: number;
29
+ readonly session?: string;
30
+ readonly subject?: string;
31
+ }
32
+ export interface WebOAuthOptions {
33
+ issuer: string;
34
+ clientId: string;
35
+ clientSecret?: string;
36
+ redirectUri: string;
37
+ postLogoutRedirectUri: string;
38
+ requestEmail?: boolean;
39
+ transactions: WebLoginStore;
40
+ recordLogout(event: WebLogoutEvent): Awaitable<boolean>;
41
+ fetch?: typeof fetch;
42
+ }
43
+ export interface WebOAuth {
44
+ beginLogin(returnTo?: string): Promise<{
45
+ authorizationUrl: string;
46
+ binding: string;
47
+ expiresAt: number;
48
+ }>;
49
+ completeLogin(callbackUrl: string, binding: string): Promise<{
50
+ identity: WebIdentity;
51
+ returnTo: string;
52
+ }>;
53
+ logoutUrl(): Promise<string>;
54
+ handleBackchannelLogout(token: string): Promise<WebLogoutEvent>;
55
+ }
56
+ export declare function createWebOAuth(options: WebOAuthOptions): WebOAuth;
package/dist/web.js ADDED
@@ -0,0 +1,185 @@
1
+ import { jwtVerify } from 'jose';
2
+ import * as oidc from 'openid-client';
3
+ import { OAuthIntegrationError } from './errors.js';
4
+ import { clientIdentifier, epoch, exactText, https, issuerAccess, nowSeconds, protocolFailure, } from './issuer.js';
5
+ const logoutEvent = 'http://schemas.openid.net/event/backchannel-logout';
6
+ const transactionId = /^[A-Za-z0-9_-]{43}$/;
7
+ const transactionLifetime = 300;
8
+ function safeReturnPath(value, origin) {
9
+ if (!exactText(value, 2048) || !value.startsWith('/') || value.startsWith('//'))
10
+ return false;
11
+ const path = value.split(/[?#]/, 1)[0] ?? '';
12
+ if (/\\|%2f|%5c|%25/i.test(path))
13
+ return false;
14
+ const url = URL.parse(value, origin);
15
+ return url?.origin === origin && !url.pathname.startsWith('//');
16
+ }
17
+ async function store(operation) {
18
+ try {
19
+ return await operation();
20
+ }
21
+ catch {
22
+ throw new OAuthIntegrationError('unavailable');
23
+ }
24
+ }
25
+ export function createWebOAuth(options) {
26
+ const { issuer, clientId, clientSecret, redirectUri, postLogoutRedirectUri, requestEmail = false, } = options;
27
+ const callback = https(redirectUri);
28
+ const signedOut = https(postLogoutRedirectUri);
29
+ if (!callback ||
30
+ !signedOut ||
31
+ !clientIdentifier(clientId) ||
32
+ (clientSecret !== undefined && !exactText(clientSecret, 4096)) ||
33
+ typeof requestEmail !== 'boolean' ||
34
+ typeof options.transactions?.save !== 'function' ||
35
+ typeof options.transactions?.take !== 'function' ||
36
+ typeof options.recordLogout !== 'function')
37
+ throw new OAuthIntegrationError('invalid_configuration');
38
+ const transactions = options.transactions;
39
+ const discovery = issuerAccess(options, {
40
+ id: clientId,
41
+ ...(clientSecret === undefined ? {} : { secret: clientSecret }),
42
+ });
43
+ return {
44
+ async beginLogin(returnTo = '/') {
45
+ if (!safeReturnPath(returnTo, callback.origin))
46
+ throw new OAuthIntegrationError('invalid_login');
47
+ const { config } = await discovery();
48
+ const binding = oidc.randomState();
49
+ const state = oidc.randomState();
50
+ const nonce = oidc.randomNonce();
51
+ const verifier = oidc.randomPKCECodeVerifier();
52
+ const expiresAt = nowSeconds() + transactionLifetime;
53
+ const url = oidc.buildAuthorizationUrl(config, {
54
+ redirect_uri: redirectUri,
55
+ scope: requestEmail ? 'openid email' : 'openid',
56
+ state,
57
+ nonce,
58
+ code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
59
+ code_challenge_method: 'S256',
60
+ });
61
+ await store(() => transactions.save(binding, {
62
+ issuer,
63
+ clientId,
64
+ redirectUri,
65
+ state,
66
+ nonce,
67
+ verifier,
68
+ returnTo,
69
+ expiresAt,
70
+ ...(requestEmail ? { emailRequested: true } : {}),
71
+ }));
72
+ return { authorizationUrl: url.href, binding, expiresAt };
73
+ },
74
+ async completeLogin(callbackUrl, binding) {
75
+ const url = exactText(callbackUrl, 8192) ? URL.parse(callbackUrl) : null;
76
+ const state = url?.searchParams.get('state');
77
+ if (!url ||
78
+ url.origin + url.pathname !== redirectUri ||
79
+ url.username ||
80
+ url.password ||
81
+ callbackUrl.includes('#') ||
82
+ !transactionId.test(binding) ||
83
+ !state ||
84
+ !transactionId.test(state) ||
85
+ new Set(url.searchParams.keys()).size !== url.searchParams.size)
86
+ throw new OAuthIntegrationError('invalid_login');
87
+ const { config } = await discovery();
88
+ const flow = await store(() => transactions.take(binding, state));
89
+ if (!flow ||
90
+ flow.state !== state ||
91
+ flow.issuer !== issuer ||
92
+ flow.clientId !== clientId ||
93
+ flow.redirectUri !== redirectUri ||
94
+ !transactionId.test(flow.nonce) ||
95
+ !transactionId.test(flow.verifier) ||
96
+ !epoch(flow.expiresAt) ||
97
+ flow.expiresAt <= nowSeconds() ||
98
+ !safeReturnPath(flow.returnTo, callback.origin))
99
+ throw new OAuthIntegrationError('invalid_login');
100
+ const tokens = await oidc
101
+ .authorizationCodeGrant(config, url, {
102
+ expectedState: flow.state,
103
+ expectedNonce: flow.nonce,
104
+ pkceCodeVerifier: flow.verifier,
105
+ })
106
+ .catch((error) => {
107
+ throw protocolFailure(error, 'invalid_login');
108
+ });
109
+ const claims = tokens.claims();
110
+ if (claims?.iss !== issuer ||
111
+ !exactText(claims.sub) ||
112
+ !exactText(claims.sid, 128) ||
113
+ !epoch(claims.iat) ||
114
+ claims.iat > nowSeconds() + 30)
115
+ throw new OAuthIntegrationError('invalid_login');
116
+ const verifiedEmail = requestEmail &&
117
+ flow.emailRequested === true &&
118
+ claims.email_verified === true &&
119
+ exactText(claims.email, 254) &&
120
+ /^[^\s@<>]+@[^\s@<>]+$/u.test(claims.email)
121
+ ? claims.email
122
+ : undefined;
123
+ return {
124
+ identity: {
125
+ issuer,
126
+ subject: claims.sub,
127
+ session: claims.sid,
128
+ issuedAt: claims.iat,
129
+ ...(verifiedEmail === undefined ? {} : { verifiedEmail }),
130
+ },
131
+ returnTo: flow.returnTo,
132
+ };
133
+ },
134
+ async logoutUrl() {
135
+ const { config } = await discovery();
136
+ if (!config.serverMetadata().end_session_endpoint)
137
+ throw new OAuthIntegrationError('unavailable');
138
+ return oidc.buildEndSessionUrl(config, {
139
+ client_id: clientId,
140
+ post_logout_redirect_uri: signedOut.href,
141
+ }).href;
142
+ },
143
+ async handleBackchannelLogout(token) {
144
+ if (!exactText(token, 8192))
145
+ throw new OAuthIntegrationError('invalid_logout');
146
+ const { keys } = await discovery();
147
+ const { payload } = await jwtVerify(token, keys, {
148
+ issuer,
149
+ audience: clientId,
150
+ algorithms: ['RS256'],
151
+ maxTokenAge: transactionLifetime,
152
+ clockTolerance: 30,
153
+ requiredClaims: ['iat', 'jti', 'events'],
154
+ }).catch((error) => {
155
+ throw protocolFailure(error, 'invalid_logout');
156
+ });
157
+ const { events, sid, sub, jti, iat, aud, azp } = payload;
158
+ const event = events && typeof events === 'object' && !Array.isArray(events)
159
+ ? events[logoutEvent]
160
+ : undefined;
161
+ if (!event ||
162
+ typeof event !== 'object' ||
163
+ Array.isArray(event) ||
164
+ Object.hasOwn(payload, 'nonce') ||
165
+ !exactText(jti, 128) ||
166
+ !epoch(iat) ||
167
+ (sid === undefined && sub === undefined) ||
168
+ (sid !== undefined && !exactText(sid, 128)) ||
169
+ (sub !== undefined && !exactText(sub)) ||
170
+ (((Array.isArray(aud) && aud.length > 1) || azp !== undefined) && azp !== clientId))
171
+ throw new OAuthIntegrationError('invalid_logout');
172
+ const notification = Object.freeze({
173
+ issuer,
174
+ clientId,
175
+ id: jti,
176
+ issuedAt: iat,
177
+ ...(sid === undefined ? {} : { session: sid }),
178
+ ...(sub === undefined ? {} : { subject: sub }),
179
+ });
180
+ if ((await store(() => options.recordLogout(notification))) !== true)
181
+ throw new OAuthIntegrationError('invalid_logout');
182
+ return notification;
183
+ },
184
+ };
185
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@agentxgo/oauth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-preview.2",
4
+ "author": "agentxgo team",
5
+ "description": "OAuth and OIDC integration tools for AgentXGo applications",
6
+ "private": false,
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=22.12.0"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ },
16
+ "./web": {
17
+ "types": "./dist/web.d.ts",
18
+ "default": "./dist/web.js"
19
+ },
20
+ "./mcp": {
21
+ "types": "./dist/mcp.d.ts",
22
+ "default": "./dist/mcp.js"
23
+ },
24
+ "./v1": {
25
+ "types": "./dist/v1.d.ts",
26
+ "default": "./dist/v1.js"
27
+ },
28
+ "./v1/example": "./dist/native-application-v1.example.json"
29
+ },
30
+ "types": "./dist/index.d.ts",
31
+ "bin": {
32
+ "agentxgo-oauth": "./dist/bin.js"
33
+ },
34
+ "dependencies": {
35
+ "jose": "6.2.12",
36
+ "openid-client": "6.8.7"
37
+ }
38
+ }