@tnunamak/dalan 0.0.0-stage → 0.6.0
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/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/as.mjs
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
1
|
+
import { uaToken } from './mcp-outcome.mjs';
|
|
2
|
+
const GRANT_TYPES = ['authorization_code', 'refresh_token', 'client_credentials'];
|
|
3
|
+
const TOKEN_PARAMS = ['grant_type', 'code', 'redirect_uri', 'client_id', 'client_secret', 'code_verifier', 'refresh_token', 'scope', 'resource', 'client_assertion', 'client_assertion_type'];
|
|
4
|
+
import { Provider, errors } from 'oidc-provider';
|
|
5
|
+
import { ACCEPTED_SCOPES, ADVERTISED_SCOPES, canonicalScopes } from './scopes.mjs';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { performance } from 'node:perf_hooks';
|
|
8
|
+
import { acquireAsOwner, asFiles, LIFETIMES, PAIRING_MINUTES, loadAsConfig, loadKeys, isLoopbackCallback, matchesCallback, parseAsConfig, parseCallbackPattern, parseNativeLoopback, saveAsCallbacks, untrusted } from './as-files.mjs';
|
|
9
|
+
import { AsStore, LIMITS, normalizeCode, showCode } from './as-store.mjs';
|
|
10
|
+
|
|
11
|
+
// The built-in authorization server. The protocol (registration, PKCE, codes, tokens, rotation, revocation) is the maintained
|
|
12
|
+
// oidc-provider library. This file holds only configuration, the owner-approval policy around it, and the lookup that turns a
|
|
13
|
+
// bearer token into an approved connection. It implements no OAuth protocol cryptography.
|
|
14
|
+
export const SCOPES = ADVERTISED_SCOPES;
|
|
15
|
+
export const ACCOUNT = 'owner';
|
|
16
|
+
const ACCESS_TOKEN_TTL = 3600;
|
|
17
|
+
const OFF = Object.freeze({ enabled: false });
|
|
18
|
+
const html = text => String(text).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
19
|
+
export { untrusted };
|
|
20
|
+
const SECURITY_HEADERS = Object.freeze({
|
|
21
|
+
'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer', 'x-frame-options': 'DENY',
|
|
22
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
|
|
23
|
+
});
|
|
24
|
+
// Metadata that would make the server fetch a URL or hold extra trust. None of these is supported (the library only reads them when a feature that is off uses them).
|
|
25
|
+
const FORBIDDEN_METADATA = ['jwks_uri', 'jwks', 'sector_identifier_uri', 'request_uris', 'initiate_login_uri', 'post_logout_redirect_uris', 'backchannel_logout_uri', 'frontchannel_logout_uri'];
|
|
26
|
+
|
|
27
|
+
function page(res, status, title, body, { refresh = 0 } = {}) {
|
|
28
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) res.setHeader(name, value);
|
|
29
|
+
res.writeHead(status, { 'content-type': 'text/html; charset=utf-8' });
|
|
30
|
+
res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${refresh ? `<meta http-equiv="refresh" content="${refresh}">` : ''}<title>${html(title)}</title>
|
|
31
|
+
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:34rem;margin:3rem auto;padding:0 1rem}.code{font:700 2rem/1.2 ui-monospace,monospace;letter-spacing:.1em}pre{background:#eee;padding:.6rem;overflow:auto}</style></head><body><h1>${html(title)}</h1>${body}</body></html>`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createAs(options) {
|
|
35
|
+
const owner = options.owner ?? acquireAsOwner(options.dir);
|
|
36
|
+
try { return createOwnedAs(options, owner); }
|
|
37
|
+
catch (error) { owner.release(); throw error; }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createOwnedAs({ dir, resource, allowHttp = false, loopback = false, workerNames, log = () => {}, now = Date.now, onConnectionRevoked = () => {} }, owner) {
|
|
41
|
+
const config = loadAsConfig(dir, { allowHttp, loopback });
|
|
42
|
+
// Ownership precedes every key-state write and stays held while this provider can sign.
|
|
43
|
+
owner.pruneKeys(now());
|
|
44
|
+
const keys = loadKeys(dir); // missing, damaged or non-working keys stop the start
|
|
45
|
+
const files = asFiles(dir);
|
|
46
|
+
const store = new AsStore(files.db, { now, limits: config.limits });
|
|
47
|
+
const publicUrl = new URL(config.public_url);
|
|
48
|
+
const resourceUrl = new URL(resource);
|
|
49
|
+
if (!/^\/[^/]+\/mcp$/.test(resourceUrl.pathname) || resourceUrl.search || resourceUrl.hash) throw new Error('as: resource needs a secret path prefix and /mcp');
|
|
50
|
+
const PREFIX = `${resourceUrl.pathname.slice(0, -4)}/oauth`;
|
|
51
|
+
const issuer = `${publicUrl.origin}${PREFIX}`;
|
|
52
|
+
const secure = publicUrl.protocol === 'https:';
|
|
53
|
+
if (!secure && !allowHttp && !loopback) throw new Error('as: an http public_url needs the explicit test flag');
|
|
54
|
+
let patterns = config.patterns;
|
|
55
|
+
if (new URL(resource).origin !== publicUrl.origin) throw new Error('as: resource must live on the public URL');
|
|
56
|
+
const callbackAllowed = uri => matchesCallback(patterns, uri);
|
|
57
|
+
// Native registrations ignore only the port; the approved request still binds the full redirect URI.
|
|
58
|
+
const registeredRedirectAllowed = (client, redirect) => client?.redirectUris?.some(uri => {
|
|
59
|
+
if(uri===redirect)return true;
|
|
60
|
+
try {
|
|
61
|
+
const requested = parseNativeLoopback(redirect);
|
|
62
|
+
const registered = parseNativeLoopback(uri);
|
|
63
|
+
return requested.loopback && registered.loopback
|
|
64
|
+
&& requested.hostname === registered.hostname && requested.pathname === registered.pathname;
|
|
65
|
+
} catch { return false; }
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
const policy = (ctx, metadata) => {
|
|
69
|
+
if (Buffer.byteLength(JSON.stringify(metadata)) > 4096 || (metadata.client_name?.length ?? 0) > 128 || (metadata.redirect_uris?.length ?? 0) > 8 || metadata.redirect_uris?.some(uri => uri.length > 512)) throw new errors.InvalidClientMetadata('client metadata exceeds the size limit');
|
|
70
|
+
if (!metadata.redirect_uris?.length) throw new errors.InvalidClientMetadata('redirect_uris is required');
|
|
71
|
+
for (const uri of metadata.redirect_uris) {
|
|
72
|
+
if (!callbackAllowed(uri)) {
|
|
73
|
+
log({ kind: 'as_registration_refused' });
|
|
74
|
+
throw new errors.InvalidClientMetadata('redirect_uris must each match an allowed vendor callback (dalan connect allow-callback)');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const nativeRedirects = metadata.redirect_uris.map(uri => isLoopbackCallback(new URL(uri)));
|
|
78
|
+
if (nativeRedirects.some(Boolean) && !nativeRedirects.every(Boolean)) throw new errors.InvalidClientMetadata('native and HTTPS redirect URIs cannot be mixed');
|
|
79
|
+
// Some vendors register as non-web clients. The callbacks above are exact allowlisted https vendor URLs, so the
|
|
80
|
+
// client behaves as a web client here: normalize it rather than refuse. Anything else stays refused.
|
|
81
|
+
if (metadata.redirect_uris.every(uri => isLoopbackCallback(new URL(uri)))) {
|
|
82
|
+
metadata.application_type = 'native';
|
|
83
|
+
} else if (metadata.application_type !== 'web') {
|
|
84
|
+
if (!metadata.redirect_uris.every(uri => uri.startsWith('https://'))) throw new errors.InvalidClientMetadata('only web clients are supported');
|
|
85
|
+
metadata.application_type = 'web';
|
|
86
|
+
}
|
|
87
|
+
for (const key of FORBIDDEN_METADATA) {
|
|
88
|
+
const value = metadata[key];
|
|
89
|
+
if (value !== undefined && !(Array.isArray(value) && !value.length)) throw new errors.InvalidClientMetadata(`${key} is not supported`);
|
|
90
|
+
}
|
|
91
|
+
for (const type of metadata.grant_types ?? []) if (!['authorization_code', 'refresh_token'].includes(type)) throw new errors.InvalidClientMetadata('grant_types may only be authorization_code and refresh_token');
|
|
92
|
+
if (ctx.oidc?.route === 'registration' && store.clientCount() >= LIMITS.clients) throw new errors.InvalidClientMetadata('the client registration limit is reached');
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const configuration = {
|
|
96
|
+
adapter: store.Adapter,
|
|
97
|
+
jwks: keys.jwks,
|
|
98
|
+
cookies: {
|
|
99
|
+
keys: keys.cookieKeys,
|
|
100
|
+
long: { httpOnly: true, sameSite: 'lax', secure },
|
|
101
|
+
short: { httpOnly: true, sameSite: 'lax', secure },
|
|
102
|
+
},
|
|
103
|
+
clients: [],
|
|
104
|
+
// Public web clients only: PKCE replaces a client secret. No other client authentication method exists.
|
|
105
|
+
clientAuthMethods: ['none'],
|
|
106
|
+
clientDefaults: { grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'web', id_token_signed_response_alg: 'ES256' },
|
|
107
|
+
enabledJWA: { idTokenSigningAlgValues: ['ES256'] },
|
|
108
|
+
allowOmittingSingleRegisteredRedirectUri: false,
|
|
109
|
+
acceptQueryParamAccessTokens: false,
|
|
110
|
+
responseTypes: ['code'],
|
|
111
|
+
scopes: [...ACCEPTED_SCOPES],
|
|
112
|
+
pkce: { required: () => true }, // S256 is the only method the library supports
|
|
113
|
+
ttl: { AuthorizationCode: 600, AccessToken: ACCESS_TOKEN_TTL, RefreshToken: 30 * 86400, Grant: 90 * 86400, Interaction: LIFETIMES.interaction, Session: LIFETIMES.session, IdToken: LIFETIMES.idToken, ClientCredentials: 600, DeviceCode: 600 },
|
|
114
|
+
rotateRefreshToken: true,
|
|
115
|
+
// A connection is the owner's approval, not a browser login: its tokens must not die with the pairing session.
|
|
116
|
+
// oidc-provider's default binds them to the session unless the client asks for offline_access. Revocation stays per connection.
|
|
117
|
+
expiresWithSession: async () => false,
|
|
118
|
+
issueRefreshToken: async (ctx, client) => client.grantTypeAllowed('refresh_token'),
|
|
119
|
+
findAccount: async (ctx, sub) => sub === ACCOUNT ? { accountId: ACCOUNT, claims: async () => ({ sub: ACCOUNT }) } : undefined,
|
|
120
|
+
// Consent comes only from the grant that the owner's approval created for this very interaction, and only while its
|
|
121
|
+
// connection is active. A session, an earlier grant or a revoked connection never authorizes a new request.
|
|
122
|
+
loadExistingGrant: async ctx => {
|
|
123
|
+
const grantId = ctx.oidc.result?.consent?.grantId;
|
|
124
|
+
if (!grantId) return undefined;
|
|
125
|
+
const connection = store.connectionByGrant(grantId);
|
|
126
|
+
const client = ctx.oidc.client;
|
|
127
|
+
if (!connection || connection.revoked_at !== null || connection.client_id !== client?.clientId) return undefined;
|
|
128
|
+
const grant = await ctx.oidc.provider.Grant.find(grantId);
|
|
129
|
+
return grant && grant.accountId === ACCOUNT && grant.clientId === client.clientId ? grant : undefined;
|
|
130
|
+
},
|
|
131
|
+
interactions: { url: async (ctx, interaction) => `${PREFIX}/interaction/${interaction.uid}` },
|
|
132
|
+
extraClientMetadata: { properties: ['dot_bridge_policy'], validator: (ctx, key, value, metadata) => { if (ctx) policy(ctx, metadata); } },
|
|
133
|
+
renderError: async (ctx, out) => {
|
|
134
|
+
ctx.type = 'html';
|
|
135
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) ctx.set(name, value);
|
|
136
|
+
ctx.body = `<!doctype html><title>Error</title><h1>Error</h1><p>${html(out.error)}</p><p>${html(out.error_description ?? '')}</p>`;
|
|
137
|
+
},
|
|
138
|
+
features: {
|
|
139
|
+
devInteractions: OFF, dPoP: OFF, pushedAuthorizationRequests: OFF, rpInitiatedLogout: OFF, userinfo: OFF, introspection: OFF,
|
|
140
|
+
backchannelLogout: OFF, ciba: OFF, mTLS: OFF, attestClientAuth: OFF, clientIdMetadataDocument: OFF, claimsParameter: OFF,
|
|
141
|
+
clientCredentials: OFF, deviceFlow: OFF, encryption: OFF, fapi: OFF, jwtIntrospection: OFF, jwtResponseModes: OFF,
|
|
142
|
+
registrationManagement: OFF, richAuthorizationRequests: OFF, requestObjects: OFF, rpMetadataChoices: OFF, jwtUserinfo: OFF,
|
|
143
|
+
webMessageResponseMode: OFF, externalSigningSupport: OFF, openid4vci: OFF,
|
|
144
|
+
registration: { enabled: true, initialAccessToken: false, issueRegistrationAccessToken: false },
|
|
145
|
+
revocation: { enabled: true },
|
|
146
|
+
resourceIndicators: {
|
|
147
|
+
enabled: true,
|
|
148
|
+
defaultResource: async () => undefined,
|
|
149
|
+
useGrantedResource: async () => true,
|
|
150
|
+
getResourceServerInfo: async (ctx, indicator) => {
|
|
151
|
+
if (indicator !== resource) throw new errors.InvalidTarget();
|
|
152
|
+
return { scope: ACCEPTED_SCOPES.join(' '), audience: resource, accessTokenTTL: ACCESS_TOKEN_TTL, accessTokenFormat: 'opaque' };
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
},
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
// Serialize refresh exchanges so a duplicate cannot enter the provider before its receipt is committed.
|
|
159
|
+
let refreshTail = Promise.resolve();
|
|
160
|
+
class BridgeProvider extends Provider {
|
|
161
|
+
registerGrantType(name, handler, params, dupes) {
|
|
162
|
+
if (name !== 'refresh_token') return super.registerGrantType(name, handler, params, dupes);
|
|
163
|
+
return super.registerGrantType(name, async ctx => {
|
|
164
|
+
let release;
|
|
165
|
+
const previous = refreshTail;
|
|
166
|
+
refreshTail = new Promise(resolve => { release = resolve; });
|
|
167
|
+
await previous;
|
|
168
|
+
try {
|
|
169
|
+
const tokenValue = ctx.oidc.params.refresh_token;
|
|
170
|
+
const source = await ctx.oidc.provider.RefreshToken.find(tokenValue, { ignoreExpiration: true });
|
|
171
|
+
// Do not intercept other client authentication or sender-constrained credentials.
|
|
172
|
+
if (!source || configuration.features.dPoP.enabled || configuration.features.mTLS.enabled || configuration.features.attestClientAuth.enabled || ctx.get('dpop') || ctx.oidc.client.clientAuthMethod !== 'none' || source.jkt || source['x5t#S256'] || source.attestationJkt) return await handler(ctx);
|
|
173
|
+
const clientId = ctx.oidc.client.clientId;
|
|
174
|
+
const fingerprint = JSON.stringify([issuer, resource, Object.fromEntries(Object.keys(ctx.oidc.params).sort().map(key => [key, ctx.oidc.params[key]]))]);
|
|
175
|
+
const receipt = source.consumed && store.refreshReceipt(tokenValue);
|
|
176
|
+
const retry = receipt && receipt.grant_id === source.grantId && receipt.value.clientId === clientId &&
|
|
177
|
+
receipt.value.params === fingerprint && store.refreshValid(source.grantId, clientId, receipt.value.response.refresh_token);
|
|
178
|
+
if (source.consumed && !retry) return await handler(ctx);
|
|
179
|
+
const exchange = { reads: [], writes: [], retryToken: retry ? tokenValue : undefined };
|
|
180
|
+
try { await store.refreshExchange.run(exchange, () => handler(ctx)); }
|
|
181
|
+
catch (error) {
|
|
182
|
+
// A rejected resource was checked after consume in the provider. Preserve that
|
|
183
|
+
// replay behavior; internal failures leave the original token untouched.
|
|
184
|
+
if (!retry && error instanceof errors.InvalidTarget) store.commitFailedRefresh(exchange);
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
if (source.exp * 1000 <= Date.now()) throw new errors.InvalidGrant('refresh token expired');
|
|
188
|
+
if (retry) {
|
|
189
|
+
if (!store.refreshReceipt(tokenValue)) return await handler(ctx);
|
|
190
|
+
if (!store.refreshValid(source.grantId, clientId, receipt.value.response.refresh_token) ||
|
|
191
|
+
exchange.reads.some(([model, id, original]) => JSON.stringify(store.find(model, id)) !== original)) throw new errors.InvalidGrant('refresh state changed');
|
|
192
|
+
ctx.body = receipt.value.response;
|
|
193
|
+
} else {
|
|
194
|
+
store.commitRefresh(exchange, source.grantId, clientId, tokenValue, fingerprint, ctx.body, now() + 5000);
|
|
195
|
+
}
|
|
196
|
+
} finally { release(); }
|
|
197
|
+
}, params, dupes);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const provider = new BridgeProvider(issuer, configuration);
|
|
201
|
+
provider.proxy = true; // Protocol and host come from the headers that this file writes, never from the client's
|
|
202
|
+
provider.use(async (ctx, next) => {
|
|
203
|
+
// The router ignores case and a trailing slash, so compare the normalised path. The store refuses to persist an interaction
|
|
204
|
+
// outside an open window as well (as-store.mjs), so no spelling of the route can create one.
|
|
205
|
+
const route = ctx.path.toLowerCase().replace(/\/+$/, '');
|
|
206
|
+
const refuse = (status, title, text) => { ctx.status = status; ctx.type = 'html'; ctx.body = `<!doctype html><title>${title}</title><h1>${title}</h1><p>${text}</p>`; };
|
|
207
|
+
if (route === '/reg' && ctx.method === 'POST') {
|
|
208
|
+
const reject = (status, error, description) => { ctx.status = status; ctx.body = { error, error_description: description }; };
|
|
209
|
+
if (!store.window()) return reject(403, 'access_denied', 'Open a pairing window before registering.');
|
|
210
|
+
if (!store.reserveRegistration()) return reject(429, 'temporarily_unavailable', 'Registration limit reached. Reuse the client this worker already registered. If you cannot, ask the owner to run dalan connect reset, then retry.');
|
|
211
|
+
if (Number(ctx.get('content-length')) > 8192) return reject(413, 'invalid_client_metadata', 'Registration body exceeds 8192 bytes.');
|
|
212
|
+
const normalized = await normalizeRegistration(ctx.req);
|
|
213
|
+
if (normalized === 'too_large') { ctx.req.destroy(); return; }
|
|
214
|
+
if (normalized === 'invalid') return reject(400, 'invalid_request', 'The registration body must be a UTF-8 JSON object.');
|
|
215
|
+
let bytes = 0;
|
|
216
|
+
const count = chunk => { bytes += chunk.length; if (bytes > 8192) ctx.req.destroy(); };
|
|
217
|
+
ctx.req.on('data', count);
|
|
218
|
+
try { await next(); } finally { ctx.req.off('data', count); }
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (route === '/token' && ctx.method === 'POST') {
|
|
222
|
+
await next();
|
|
223
|
+
// Names and shapes only, never a value of a secret: what a client sent and what it was given back.
|
|
224
|
+
// Names come from fixed lists: a caller chooses the text of grant_type and the names of its parameters, so neither is logged as sent.
|
|
225
|
+
const sent = ctx.oidc?.body ?? {}, given = ctx.body && typeof ctx.body === 'object' ? ctx.body : {};
|
|
226
|
+
const names = Object.keys(sent), known = names.filter(k => TOKEN_PARAMS.includes(k)).sort();
|
|
227
|
+
log({ kind: 'as_token_detail', status: ctx.status, grant_type: typeof sent.grant_type === 'string' ? (GRANT_TYPES.includes(sent.grant_type) ? sent.grant_type : 'other') : null, request_params: known, unknown_params: names.length - known.length, response_has: ['access_token', 'refresh_token', 'id_token', 'scope', 'expires_in', 'token_type'].filter(k => given[k] !== undefined).map(k => k.replace('_token', 'Tok')), token_type: given.token_type === 'Bearer' ? 'Bearer' : null, scope: typeof given.scope === 'string' ? given.scope.split(' ').filter(x => ACCEPTED_SCOPES.includes(x) || x === 'openid').join(' ') : null, expires_in: Number.isInteger(given.expires_in) ? given.expires_in : null, has_resource: Boolean(sent.resource) });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (route === '/auth' && ctx.query.response_type !== 'code') return refuse(400, 'Unsupported response type', 'Only response_type=code is supported.');
|
|
231
|
+
if (route === '/auth' || route.startsWith('/auth/')) {
|
|
232
|
+
// Only response_mode=query is supported: form_post would need a script-free page the CSP cannot allow.
|
|
233
|
+
const mode = ctx.query.response_mode;
|
|
234
|
+
if (mode !== undefined && mode !== 'query') {
|
|
235
|
+
ctx.status = 400; ctx.type = 'html';
|
|
236
|
+
ctx.body = '<!doctype html><title>Unsupported response mode</title><h1>Unsupported response mode</h1><p>Only response_mode=query is supported.</p>';
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (route === '/auth' && store.window() && store.interactionsFull()) {
|
|
241
|
+
ctx.set('retry-after', '60');
|
|
242
|
+
return refuse(503, 'Busy', 'Too many connection attempts are waiting. Ask the owner to run dalan connect reset, then retry.');
|
|
243
|
+
}
|
|
244
|
+
if (route === '/auth' && !store.window()) {
|
|
245
|
+
ctx.status = 403; ctx.type = 'html';
|
|
246
|
+
ctx.body = '<!doctype html><title>Not accepting connections</title><h1>Not accepting connections</h1><p>This bridge is not accepting new connections right now.</p>';
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
await next();
|
|
250
|
+
// Discovery tells the truth about what this server accepts (the library lists modes and types it also supports).
|
|
251
|
+
if (ctx.body && typeof ctx.body === 'object' && ctx.body.issuer === issuer && ctx.body.authorization_endpoint) {
|
|
252
|
+
ctx.body = { ...ctx.body, response_modes_supported: ['query'], response_types_supported: ['code'] };
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
store.onGrantRevoked = (grantId, reason) => {
|
|
256
|
+
log({ kind: 'as_grant_revoked', reason });
|
|
257
|
+
const connection=store.connectionByGrant(grantId);
|
|
258
|
+
if(connection) onConnectionRevoked(connection.connection_id,reason);
|
|
259
|
+
};
|
|
260
|
+
provider.on('grant.revoked', (ctx, grantId) => store.revokeGrant(grantId, 'grant_revoked'));
|
|
261
|
+
for (const event of ['server_error', 'authorization.error', 'grant.error', 'registration_create.error']) {
|
|
262
|
+
provider.on(event, (ctx, error) => {
|
|
263
|
+
// Provider error text and field names can contain request secrets.
|
|
264
|
+
log({ kind: 'as_error', event });
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
const callback = provider.callback();
|
|
268
|
+
const purge = () => { try { const r = store.purge(); if (r.expired || r.stale_clients) log({ kind: 'as_purge', ...r }); } catch { log({ kind: 'as_purge_error' }); } };
|
|
269
|
+
purge();
|
|
270
|
+
const purgeTimer = setInterval(purge, 600000); purgeTimer.unref();
|
|
271
|
+
|
|
272
|
+
// ---- public HTTP surface --------------------------------------------------------------------------------------
|
|
273
|
+
const hostOk = req => String(req.headers.host ?? '').toLowerCase() === publicUrl.host.toLowerCase();
|
|
274
|
+
const WELL_KNOWN = { [`/.well-known/oauth-authorization-server${PREFIX}`]: '/.well-known/oauth-authorization-server', [`/.well-known/openid-configuration${PREFIX}`]: '/.well-known/openid-configuration' };
|
|
275
|
+
const interactionPath = /^\/interaction\/([A-Za-z0-9_-]{10,64})$/;
|
|
276
|
+
|
|
277
|
+
async function handle(req, res) {
|
|
278
|
+
const pathname = req.url.split('?')[0];
|
|
279
|
+
const alias = WELL_KNOWN[pathname];
|
|
280
|
+
if (!alias && pathname !== PREFIX && !pathname.startsWith(`${PREFIX}/`)) return false;
|
|
281
|
+
const interaction = interactionPath.exec(pathname.slice(PREFIX.length));
|
|
282
|
+
// One line per request with a fixed route name and the status, never a path, query or body: a connection that stalls after
|
|
283
|
+
// approval can then be told apart (no token request vs a refused one) without the log holding a secret.
|
|
284
|
+
const routeName = alias ? 'discovery' : ({ '/reg': 'registration', '/auth': 'authorize', '/token': 'token', '/token/revocation': 'revocation', '/jwks': 'jwks' }[pathname.slice(PREFIX.length).toLowerCase().replace(/\/+$/, '')]
|
|
285
|
+
?? (interaction ? 'interaction' : pathname.slice(PREFIX.length).startsWith('/auth/') ? 'authorize_resume' : 'other'));
|
|
286
|
+
res.once('finish', () => log({ kind: 'as_request', route: routeName, http_method: req.method, status: res.statusCode, ua: uaToken(req) }));
|
|
287
|
+
try {
|
|
288
|
+
if (interaction) await interactionPage(req, res, interaction[1]);
|
|
289
|
+
else await provide(req, res, alias);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
log({ kind: 'as_handler_error' });
|
|
292
|
+
if (!res.headersSent) page(res, 500, 'Error', '<p>The request failed.</p>'); else res.destroy();
|
|
293
|
+
}
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
// Every client here is public (PKCE, no secret). RFC 7591 §2 makes `client_secret_basic` the default when a registration omits
|
|
297
|
+
// `token_endpoint_auth_method`, and the library then issues a secret that the token endpoint and the metadata (only `none`)
|
|
298
|
+
// would never accept. RFC 7591 §3.2.1 lets the server replace requested values as long as the response shows what it registered,
|
|
299
|
+
// so an omitted or unsupported method is registered as `none`: the response carries `token_endpoint_auth_method: "none"` and no
|
|
300
|
+
// `client_secret`, in agreement with the metadata and the token endpoint. A strict client (claude.ai) stops on that mismatch.
|
|
301
|
+
// Returns 'ok', or 'invalid' for a body that is not a UTF-8 JSON object (the caller answers it as the library answers a bad body).
|
|
302
|
+
async function normalizeRegistration(req) {
|
|
303
|
+
const type = req.headers['content-type'] ?? '';
|
|
304
|
+
if (!/^application\/json\b/i.test(type)) return 'ok';
|
|
305
|
+
const charset = /;\s*charset\s*=\s*"?([^";\s]+)/i.exec(type)?.[1];
|
|
306
|
+
if (charset && !/^utf-?8$/i.test(charset)) return 'invalid';
|
|
307
|
+
const chunks = []; let size = 0;
|
|
308
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) { size += chunk.length; if (size > 8192) return 'too_large'; chunks.push(chunk); }
|
|
309
|
+
let body;
|
|
310
|
+
try { body = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))); } catch { return 'invalid'; }
|
|
311
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) return 'invalid'; // parsed once, here; a JSON string is never parsed again
|
|
312
|
+
if (body.token_endpoint_auth_method !== 'none') body.token_endpoint_auth_method = 'none';
|
|
313
|
+
delete body.client_secret; delete body.client_secret_expires_at;
|
|
314
|
+
req.body = body;
|
|
315
|
+
return 'ok';
|
|
316
|
+
}
|
|
317
|
+
async function provide(req, res, alias) {
|
|
318
|
+
if (alias && !['GET', 'HEAD'].includes(req.method)) { res.writeHead(405, { allow: 'GET, HEAD' }); res.end(); return; }
|
|
319
|
+
for (const name of Object.keys(req.headers)) if (name === 'forwarded' || name === 'x-real-ip' || name.startsWith('x-forwarded-')) delete req.headers[name];
|
|
320
|
+
req.headers['x-forwarded-proto'] = publicUrl.protocol.slice(0, -1);
|
|
321
|
+
req.headers['x-forwarded-host'] = publicUrl.host;
|
|
322
|
+
req.originalUrl = req.url;
|
|
323
|
+
req.baseUrl = PREFIX;
|
|
324
|
+
req.url = alias ? alias : (req.url.slice(PREFIX.length) || '/');
|
|
325
|
+
if (!req.url.startsWith('/')) req.url = `/${req.url}`;
|
|
326
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS)) res.setHeader(name, value);
|
|
327
|
+
await store.admission.run(store.window()?.generation, () => callback(req, res));
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ---- the browser's side of an interaction ---------------------------------------------------------------------
|
|
331
|
+
const sameRequest = (pairing, params, client) => {
|
|
332
|
+
const scopes = requestedScopes(params.scope);
|
|
333
|
+
return params.client_id === pairing.client_id && params.redirect_uri === pairing.redirect_uri && scopes.join(' ') === pairing.scopes
|
|
334
|
+
&& params.resource === pairing.resource && (params.response_mode === undefined || params.response_mode === 'query') && registeredRedirectAllowed(client, pairing.redirect_uri) && callbackAllowed(pairing.redirect_uri);
|
|
335
|
+
};
|
|
336
|
+
// `openid` is the one scope the server lists itself. A client may ask for it; the grant then carries it. Any other scope is ignored.
|
|
337
|
+
const requestedScopes = scope => [...new Set(String(scope ?? '').split(' ').filter(s => ACCEPTED_SCOPES.includes(s) || s === 'openid'))];
|
|
338
|
+
async function interactionPage(req, res, uid) {
|
|
339
|
+
if (req.method !== 'GET') { res.writeHead(405, { allow: 'GET' }); res.end(); return; }
|
|
340
|
+
let details;
|
|
341
|
+
try { details = await provider.interactionDetails(req, res); } catch { return page(res, 400, 'Connection attempt invalid or expired', `<p>This connection attempt is invalid or expired. Attempts last ${PAIRING_MINUTES} minutes. If yours ran out, ask the bridge owner to start a new one. Start a new connection from the app.</p>`); }
|
|
342
|
+
// The cookie names the interaction. The path must name the same one.
|
|
343
|
+
if (details.uid !== uid) return page(res, 400, 'Connection attempt invalid or expired', `<p>This connection attempt is invalid or expired. Attempts last ${PAIRING_MINUTES} minutes. If yours ran out, ask the bridge owner to start a new one. Start a new connection from the app.</p>`);
|
|
344
|
+
const window = store.window();
|
|
345
|
+
let pairing = store.pairingByUid(uid);
|
|
346
|
+
const client = await provider.Client.find(details.params.client_id);
|
|
347
|
+
if (!pairing) {
|
|
348
|
+
if (!window) return page(res, 403, 'Not accepting connections', '<p>This bridge is not accepting new connections right now.</p>');
|
|
349
|
+
const scopes = requestedScopes(details.params.scope);
|
|
350
|
+
const redirect = details.params.redirect_uri;
|
|
351
|
+
if (!scopes.some(s => ACCEPTED_SCOPES.includes(s))) return page(res, 400, 'No usable scope', '<p>The app asked for no scope that this bridge offers.</p>');
|
|
352
|
+
if (!client || !registeredRedirectAllowed(client, redirect) || !callbackAllowed(redirect)) return page(res, 400, 'Callback not allowed', '<p>The app\'s callback address is not on this bridge\'s allowed list.</p>');
|
|
353
|
+
if (details.params.resource !== resource) return page(res, 400, 'Wrong resource', '<p>The app did not ask for this bridge\'s resource.</p>');
|
|
354
|
+
try {
|
|
355
|
+
pairing = store.pairingFor(uid, { client_id: client.clientId, client_name: untrusted(client.clientName), redirect_uri: redirect, resource, scopes: scopes.join(' '), interaction_expires_at: details.exp * 1000 }, window);
|
|
356
|
+
} catch (error) { return page(res, 503, 'Busy', `<p>${html(error.message)}.</p>`); }
|
|
357
|
+
}
|
|
358
|
+
if (pairing.state === 'approved') return complete(req, res, details, pairing, client);
|
|
359
|
+
if (pairing.state !== 'pending' && pairing.state !== 'approving') return page(res, 410, 'Finished', '<p>This connection attempt is already finished. Start again from the app.</p>');
|
|
360
|
+
if (pairing.expires_at <= now() || (!window && store.windowExpired())) return page(res, 403, 'Connection attempt expired', `<p>This connection attempt expired. Attempts last ${PAIRING_MINUTES} minutes. Ask the bridge owner to start a new one.</p>`);
|
|
361
|
+
if (!window || window.worker !== pairing.worker) return page(res, 403, 'Not accepting connections', '<p>This bridge is not accepting new connections right now.</p>');
|
|
362
|
+
const code = showCode(pairing.code);
|
|
363
|
+
const native = isLoopbackCallback(new URL(pairing.redirect_uri));
|
|
364
|
+
page(res, 200, 'Connect to Dalan', `<p>Pairing code</p><p class="code">${html(code)}</p><p>Run approval on the bridge computer:</p><pre>dalan connect approve ${html(code)} --worker ${html(pairing.worker)}</pre>${native ? '<p>Native client, identity not verified: host and name prove nothing. The owner must compare this code with the teammate\'s browser page over a trusted channel. The redirect confirmation is only a typo check, not proof of identity.</p>' : ''}<p>This page waits. It checks again every few seconds.</p>`, { refresh: 3 });
|
|
365
|
+
}
|
|
366
|
+
async function complete(req, res, details, pairing, client) {
|
|
367
|
+
const connection = store.connectionByGrant(pairing.grant_id);
|
|
368
|
+
if (!connection || connection.revoked_at !== null || connection.client_id !== pairing.client_id || connection.redirect_uri !== pairing.redirect_uri
|
|
369
|
+
|| connection.resource !== pairing.resource || connection.scopes !== pairing.scopes || !sameRequest(pairing, details.params, client)) {
|
|
370
|
+
return page(res, 409, 'Approval no longer valid', '<p>The approved request changed or was revoked. Start again from the app.</p>');
|
|
371
|
+
}
|
|
372
|
+
// Order matters for crash recovery. The pairing stays `approved` until the provider has stored the interaction result, so a
|
|
373
|
+
// crash between the two leaves a page the browser can load again. Marking it `done` first would strand an approved connection.
|
|
374
|
+
// Repeating this step is safe: it stores the same result for the same grant, and the provider's resume step consumes the
|
|
375
|
+
// interaction, so only one authorization code can ever be issued.
|
|
376
|
+
await provider.interactionFinished(req, res, { login: { accountId: ACCOUNT, remember: false }, consent: { grantId: pairing.grant_id } }, { mergeWithLastSubmission: false });
|
|
377
|
+
store.finishPairing(pairing.uid);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ---- owner operations (called from the owner Unix socket only) -------------------------------------------------
|
|
381
|
+
// Some web apps register multiple clients during one connection flow, so an older pending web code for the same worker
|
|
382
|
+
// may no longer finish its token exchange. Those older codes stay visible, marked superseded by the newest web one.
|
|
383
|
+
// Native (loopback) pairings are never superseded: each is approved by its own code only.
|
|
384
|
+
const supersede = views => {
|
|
385
|
+
const newest = views.filter(view => !view.native).at(-1);
|
|
386
|
+
return views.map(view => view.native || view === newest ? view : { ...view, superseded: true, superseded_by: newest.code });
|
|
387
|
+
};
|
|
388
|
+
// The owner CLI never prints the bridge path secret (approve output checks this), so show the resource's origin and shape only.
|
|
389
|
+
const shownResource = resource => `${new URL(resource).origin}/<secret>/mcp`;
|
|
390
|
+
const pendingView = pairing => ({
|
|
391
|
+
code: showCode(pairing.code), worker: pairing.worker, client_id: pairing.client_id, client_name: untrusted(pairing.client_name), client_name_untrusted: true,
|
|
392
|
+
native: isLoopbackCallback(new URL(pairing.redirect_uri)),
|
|
393
|
+
redirect_uri: pairing.redirect_uri, resource: shownResource(pairing.resource), scopes: pairing.scopes.split(' '), age_seconds: Math.max(0, Math.round((now() - pairing.created_at) / 1000)),
|
|
394
|
+
expires_in_seconds: Math.max(0, Math.round((pairing.expires_at - now()) / 1000)),
|
|
395
|
+
});
|
|
396
|
+
const known = worker => typeof worker === 'string' && workerNames().includes(worker);
|
|
397
|
+
const ops = {
|
|
398
|
+
addClient({ redirectUri, name } = {}) {
|
|
399
|
+
if (!callbackAllowed(redirectUri)) throw new Error('redirect_uri must match an allowed vendor callback');
|
|
400
|
+
if (name !== undefined && (typeof name !== 'string' || name.length > 100 || !untrusted(name, 80))) throw new Error('name must be a non-empty string of at most 100 characters');
|
|
401
|
+
const metadata = {
|
|
402
|
+
client_id: randomUUID(), redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
|
|
403
|
+
token_endpoint_auth_method: 'none', application_type: isLoopbackCallback(new URL(redirectUri)) ? 'native' : 'web', ...(name !== undefined ? { client_name: untrusted(name, 80) } : {}),
|
|
404
|
+
};
|
|
405
|
+
const client = new provider.Client(metadata);
|
|
406
|
+
const persisted = client.metadata();
|
|
407
|
+
if (persisted.token_endpoint_auth_method !== 'none' || persisted.client_secret) throw new Error('static clients must use public client authentication');
|
|
408
|
+
delete persisted.client_secret;
|
|
409
|
+
delete persisted.client_secret_expires_at;
|
|
410
|
+
const createdAt = store.addStaticClient(client.clientId, persisted);
|
|
411
|
+
log({ kind: 'static_client_added', client_id: client.clientId });
|
|
412
|
+
return { client_id: client.clientId, created_at: new Date(createdAt).toISOString() };
|
|
413
|
+
},
|
|
414
|
+
clients() {
|
|
415
|
+
return { clients: store.clientRows().map(({ client_id, metadata, created_at, is_static }) => ({
|
|
416
|
+
client_id, type: is_static ? 'static' : 'dcr', client_name: untrusted(metadata.client_name), client_name_untrusted: true,
|
|
417
|
+
redirect_uris: Array.isArray(metadata.redirect_uris) ? metadata.redirect_uris : [], created_at: new Date(created_at).toISOString(),
|
|
418
|
+
})) };
|
|
419
|
+
},
|
|
420
|
+
removeClient({ clientId } = {}) {
|
|
421
|
+
if (typeof clientId !== 'string' || !/^[A-Za-z0-9_-]{8,128}$/.test(clientId)) throw new Error('invalid client ID');
|
|
422
|
+
const removed = store.removeStaticClient(clientId);
|
|
423
|
+
log({ kind: 'static_client_removed', client_id: clientId, revoked_grants: removed.revoked_grants });
|
|
424
|
+
return removed;
|
|
425
|
+
},
|
|
426
|
+
start({ worker, minutes = 10 }) {
|
|
427
|
+
if (!known(worker)) throw new Error(`unknown worker ${JSON.stringify(untrusted(worker, 64))}; configured workers: ${workerNames().join(', ')}`);
|
|
428
|
+
if (!Number.isInteger(minutes) || minutes < 1 || minutes > 60) throw new Error('minutes must be an integer from 1 to 60');
|
|
429
|
+
// An owner action: attempts left over from earlier windows are dropped. A window that is already open keeps its attempts.
|
|
430
|
+
if (!store.window()) store.purgeUnapproved();
|
|
431
|
+
const window = store.openWindow(worker, minutes);
|
|
432
|
+
return { worker, window_open: true, expires_at: new Date(window.expires_at).toISOString(), minutes };
|
|
433
|
+
},
|
|
434
|
+
reset() { return store.reset(); },
|
|
435
|
+
stop() { return { closed: store.closeWindow() }; },
|
|
436
|
+
pending() {
|
|
437
|
+
const window = store.window();
|
|
438
|
+
return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, pending: window ? supersede(store.pendingPairings().filter(p => p.worker === window.worker).map(pendingView)) : [] };
|
|
439
|
+
},
|
|
440
|
+
async approve({ code, worker, replace = false, confirm_redirect: confirmRedirect }) {
|
|
441
|
+
if (typeof code !== 'string' || normalizeCode(code).length !== 8) throw new Error('invalid pairing code');
|
|
442
|
+
if (typeof replace !== 'boolean') throw new Error('replace must be true or false');
|
|
443
|
+
const pairing = store.pairingByCode(code);
|
|
444
|
+
if (!pairing) throw new Error('unknown pairing code');
|
|
445
|
+
if (pairing.state !== 'pending') throw new Error(`pairing code is ${pairing.state === 'approving' ? 'being approved' : 'already used'}`);
|
|
446
|
+
if (pairing.expires_at <= now()) throw new Error('pairing code expired');
|
|
447
|
+
if (worker !== pairing.worker) throw new Error(`pairing code belongs to worker ${pairing.worker}, not ${JSON.stringify(untrusted(worker, 64))}`);
|
|
448
|
+
if (!known(worker)) throw new Error('unknown worker');
|
|
449
|
+
const native = isLoopbackCallback(new URL(pairing.redirect_uri));
|
|
450
|
+
if (native && confirmRedirect !== pairing.redirect_uri) throw new Error('native callback approval requires exact redirect confirmation');
|
|
451
|
+
if (!native && confirmRedirect !== undefined) throw new Error('redirect confirmation is only valid for a native callback');
|
|
452
|
+
const window = store.window();
|
|
453
|
+
if (!window || window.worker !== worker) throw new Error('no open pairing window for this worker; run dalan connect start');
|
|
454
|
+
// The interaction and the registered client must still be exactly what the owner saw.
|
|
455
|
+
const interaction = store.find('Interaction', pairing.uid);
|
|
456
|
+
const client = await provider.Client.find(pairing.client_id);
|
|
457
|
+
if (!interaction || !sameRequest(pairing, interaction.params ?? {}, client)) throw new Error('the pending request changed or expired; not approved');
|
|
458
|
+
if (store.activeConnection(worker) && !replace) throw new Error(`worker ${worker} already has an active connection. Approving with --replace ends it and gives the new client every queued and future job for worker ${worker}, including briefs approved before the switch. Approve only a code you started yourself`);
|
|
459
|
+
if (!store.reserve(pairing.code)) {
|
|
460
|
+
if (store.pairingByCode(pairing.code)?.state === 'pending') throw new Error('pairing code was superseded by a newer attempt for this worker; approve the newest code (dalan connect pending)');
|
|
461
|
+
throw new Error('pairing code is being approved or already used');
|
|
462
|
+
}
|
|
463
|
+
let grantId;
|
|
464
|
+
try {
|
|
465
|
+
const grant = new provider.Grant({ accountId: ACCOUNT, clientId: pairing.client_id });
|
|
466
|
+
const wanted = pairing.scopes.split(' ');
|
|
467
|
+
// The owner approved exactly these scopes. With the bridge scopes in `scopes` (so DCR accepts a `scope` field), the
|
|
468
|
+
// provider also checks them as OIDC scopes at consent, so the grant carries them there too; tokens use the resource scope.
|
|
469
|
+
grant.addOIDCScope(wanted.join(' '));
|
|
470
|
+
grant.addResourceScope(pairing.resource, wanted.filter(scope => scope !== 'openid').join(' '));
|
|
471
|
+
grantId = await grant.save();
|
|
472
|
+
const { connection_id, replaced } = store.commitApproval({ code: pairing.code, worker, grantId, snapshot: pairing, replace });
|
|
473
|
+
if (replaced) store.revokeGrant(replaced.grant_id, 'replaced');
|
|
474
|
+
log({ kind: 'connection_approved', connection_id, worker, client_id: pairing.client_id, replaced: !!replaced });
|
|
475
|
+
return { approved: true, connection_id, worker, grant_id: grantId, client_id: pairing.client_id, redirect_uri: pairing.redirect_uri, scopes: pairing.scopes.split(' '), replaced: replaced?.connection_id ?? null };
|
|
476
|
+
} catch (error) {
|
|
477
|
+
store.failPairing(pairing.code);
|
|
478
|
+
if (grantId) { try { store.revokeGrant(grantId, 'approval_failed'); } catch { /* the grant has no connection row; deleting its rows is enough */ } }
|
|
479
|
+
throw error;
|
|
480
|
+
}
|
|
481
|
+
},
|
|
482
|
+
list() {
|
|
483
|
+
const window = store.window();
|
|
484
|
+
return { window: window ? { worker: window.worker, expires_at: new Date(window.expires_at).toISOString() } : null, callbacks: patterns.map(p => p.pattern),
|
|
485
|
+
connections: store.connections().map(c => ({ connection_id: c.connection_id, worker: c.worker, client_id: c.client_id, redirect_uri: c.redirect_uri, scopes: c.scopes.split(' '), created_at: new Date(c.created_at).toISOString(), revoked_at: c.revoked_at === null ? null : new Date(c.revoked_at).toISOString(), revoked_reason: c.revoked_reason })) };
|
|
486
|
+
},
|
|
487
|
+
revoke({ worker }) {
|
|
488
|
+
if (!known(worker)) throw new Error('unknown worker');
|
|
489
|
+
const connection = store.activeConnection(worker);
|
|
490
|
+
if (!connection) throw new Error(`worker ${worker} has no active connection`);
|
|
491
|
+
store.revokeGrant(connection.grant_id, 'owner_revoked');
|
|
492
|
+
log({ kind: 'connection_revoked', connection_id: connection.connection_id, worker });
|
|
493
|
+
return { revoked: true, connection_id: connection.connection_id, worker };
|
|
494
|
+
},
|
|
495
|
+
allowCallback({ pattern }) {
|
|
496
|
+
const parsed = parseCallbackPattern(pattern);
|
|
497
|
+
if (!patterns.some(p => p.pattern === parsed.pattern)) {
|
|
498
|
+
const next = [...patterns, parsed];
|
|
499
|
+
const validated = parseAsConfig({ version: 1, public_url: publicUrl.origin, callbacks: next.map(p => p.pattern), limits: config.limits }, { allowHttp, loopback, stored: true });
|
|
500
|
+
saveAsCallbacks(dir, validated.callbacks);
|
|
501
|
+
patterns = validated.patterns;
|
|
502
|
+
}
|
|
503
|
+
return { callbacks: patterns.map(p => p.pattern) };
|
|
504
|
+
},
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
// ---- the bridge's side: bearer token -> approved connection ------------------------------------------------------
|
|
508
|
+
// Opaque token -> AccessToken -> grant_id -> connection row. Anything missing, expired, revoked or different is a refusal.
|
|
509
|
+
async function verifyBearer(header, trace = {}) {
|
|
510
|
+
const start = performance.now();
|
|
511
|
+
Object.assign(trace, { auth_outcome: 'pending', auth_reason: null, auth_duration_ms: null, jwks_outcome: 'not_applicable', jwks_duration_ms: null, jwks_http_status: null });
|
|
512
|
+
let reason = 'missing_bearer';
|
|
513
|
+
try {
|
|
514
|
+
if (typeof header !== 'string' || !header.startsWith('Bearer ')) throw new Error('missing bearer token');
|
|
515
|
+
const value = header.slice(7);
|
|
516
|
+
reason = 'invalid_token';
|
|
517
|
+
if (!/^[A-Za-z0-9_-]{20,128}$/.test(value)) throw new Error('invalid bearer token');
|
|
518
|
+
const token = await provider.AccessToken.find(value);
|
|
519
|
+
if (!token || token.kind !== 'AccessToken' || token.accountId !== ACCOUNT || token.aud !== resource || !token.grantId || token.isExpired) throw new Error('invalid bearer token');
|
|
520
|
+
reason = 'connection_inactive';
|
|
521
|
+
const connection = store.connectionByGrant(token.grantId);
|
|
522
|
+
if (!connection || connection.revoked_at !== null || connection.client_id !== token.clientId || connection.resource !== resource) throw new Error('connection inactive');
|
|
523
|
+
const grant = await provider.Grant.find(token.grantId);
|
|
524
|
+
if (!grant || grant.accountId !== ACCOUNT || grant.clientId !== token.clientId) throw new Error('grant inactive');
|
|
525
|
+
reason = 'invalid_scope';
|
|
526
|
+
const granted = canonicalScopes(connection.scopes.split(' '));
|
|
527
|
+
const scopes = canonicalScopes(String(token.scope ?? '').split(' '));
|
|
528
|
+
if (!scopes.size || [...scopes].some(s => !granted.has(s))) throw new Error('invalid bearer scope');
|
|
529
|
+
trace.auth_outcome = 'success'; trace.auth_reason = 'verified';
|
|
530
|
+
return { subject: ACCOUNT, scopes, issuer, client_id: token.clientId, connection_id: connection.connection_id, builtin: true, connection: { worker: connection.worker } };
|
|
531
|
+
} catch (error) {
|
|
532
|
+
trace.auth_outcome = 'failure'; trace.auth_reason = reason;
|
|
533
|
+
throw error;
|
|
534
|
+
} finally { trace.auth_duration_ms = Math.max(0, Math.round(performance.now() - start)); }
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
return { provider, store, issuer, resource, publicUrl, config: { ...config, issuer }, hostOk, handle, ops, verifyBearer, close() { clearInterval(purgeTimer); store.close(); owner.release(); } };
|
|
538
|
+
}
|