@fabrika/iam 0.0.0-stage → 0.9.0-dev.26
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/fabrika.config.ts +267 -0
- package/migrations/0001_init.sql +316 -0
- package/migrations/0002_oauth.sql +38 -0
- package/migrations/0003_contract_apps.sql +11 -0
- package/migrations/0004_membership.sql +93 -0
- package/migrations/0005_workloads.sql +23 -0
- package/migrations/0006_membership_transport_keys.sql +16 -0
- package/migrations/0007_member_directory.sql +7 -0
- package/migrations/0008_durable_audit.sql +28 -0
- package/migrations/0009_member_lookups.sql +7 -0
- package/migrations/0010_workload_issues.sql +6 -0
- package/migrations/0011_app_presentation.sql +15 -0
- package/migrations/0012_external_principals.sql +10 -0
- package/migrations/0013_app_mail_templates.sql +14 -0
- package/migrations/0014_invitation_wording.sql +8 -0
- package/migrations/0015_app_schema_revisions.sql +15 -0
- package/migrations/0016_principal_grant_revision.sql +9 -0
- package/migrations/0017_app_sign_ins.sql +12 -0
- package/migrations/0018_app_members.sql +13 -0
- package/migrations/0019_app_mail_html.sql +7 -0
- package/migrations/0020_public_workloads.sql +34 -0
- package/migrations/0021_installation_brand.sql +19 -0
- package/migrations/0022_password_policy.sql +12 -0
- package/migrations/0023_terminals.sql +155 -0
- package/migrations/0024_app_terminals.sql +10 -0
- package/migrations/0025_terminal_completion.sql +10 -0
- package/migrations/0026_terminal_generation.sql +12 -0
- package/migrations/0027_application_exact_actions.sql +28 -0
- package/migrations/0028_oauth_client_assertions.sql +10 -0
- package/migrations/0029_role_via.sql +6 -0
- package/migrations/0030_membership_role_via.sql +12 -0
- package/migrations/0031_person_locale.sql +11 -0
- package/migrations-postgres/0001_init.sql +331 -0
- package/migrations-postgres/0002_oauth.sql +36 -0
- package/migrations-postgres/0003_contract_apps.sql +8 -0
- package/migrations-postgres/0004_membership.sql +92 -0
- package/migrations-postgres/0005_workloads.sql +18 -0
- package/migrations-postgres/0006_membership_transport_keys.sql +12 -0
- package/migrations-postgres/0007_member_directory.sql +7 -0
- package/migrations-postgres/0008_durable_audit.sql +8 -0
- package/migrations-postgres/0009_member_lookups.sql +7 -0
- package/migrations-postgres/0010_workload_issues.sql +6 -0
- package/migrations-postgres/0011_app_presentation.sql +15 -0
- package/migrations-postgres/0012_external_principals.sql +10 -0
- package/migrations-postgres/0013_app_mail_templates.sql +14 -0
- package/migrations-postgres/0014_invitation_wording.sql +8 -0
- package/migrations-postgres/0015_app_schema_revisions.sql +15 -0
- package/migrations-postgres/0016_principal_grant_revision.sql +9 -0
- package/migrations-postgres/0017_app_sign_ins.sql +12 -0
- package/migrations-postgres/0018_app_members.sql +13 -0
- package/migrations-postgres/0019_app_mail_html.sql +7 -0
- package/migrations-postgres/0020_public_workloads.sql +9 -0
- package/migrations-postgres/0021_installation_brand.sql +19 -0
- package/migrations-postgres/0022_password_policy.sql +12 -0
- package/migrations-postgres/0023_terminals.sql +70 -0
- package/migrations-postgres/0024_app_terminals.sql +10 -0
- package/migrations-postgres/0025_terminal_completion.sql +10 -0
- package/migrations-postgres/0026_terminal_generation.sql +12 -0
- package/migrations-postgres/0027_application_exact_actions.sql +28 -0
- package/migrations-postgres/0028_oauth_client_assertions.sql +9 -0
- package/migrations-postgres/0029_role_via.sql +4 -0
- package/migrations-postgres/0030_membership_role_via.sql +7 -0
- package/migrations-postgres/0031_person_locale.sql +11 -0
- package/package.json +70 -5
- package/src/admin/access.ts +47 -0
- package/src/admin/api-keys.ts +280 -0
- package/src/admin/app-people.ts +209 -0
- package/src/admin/app-schema.ts +308 -0
- package/src/admin/audit.ts +81 -0
- package/src/admin/brand.ts +54 -0
- package/src/admin/connections.ts +48 -0
- package/src/admin/context.ts +70 -0
- package/src/admin/grant-support.ts +192 -0
- package/src/admin/grants.ts +189 -0
- package/src/admin/handlers.ts +102 -0
- package/src/admin/http.ts +24 -0
- package/src/admin/membership-keys.ts +38 -0
- package/src/admin/pagination.ts +28 -0
- package/src/admin/password-policy.ts +48 -0
- package/src/admin/passwords.ts +78 -0
- package/src/admin/policies.ts +136 -0
- package/src/admin/principals.ts +226 -0
- package/src/admin/router.ts +291 -0
- package/src/admin/rpc.ts +387 -0
- package/src/admin/sessions.ts +115 -0
- package/src/admin/share-links.ts +127 -0
- package/src/admin/terminals.ts +115 -0
- package/src/admin/user-admin.ts +76 -0
- package/src/admin/workloads.ts +85 -0
- package/src/app-presentation.ts +178 -0
- package/src/app.ts +158 -0
- package/src/auth/cookies.ts +64 -0
- package/src/auth/failure.ts +25 -0
- package/src/auth/handoff.ts +136 -0
- package/src/auth/http.ts +88 -0
- package/src/auth/invitations.ts +220 -0
- package/src/auth/known-device.ts +44 -0
- package/src/auth/login.ts +162 -0
- package/src/auth/oidc-flight.ts +91 -0
- package/src/auth/oidc.ts +148 -0
- package/src/auth/password.ts +416 -0
- package/src/auth/routes.ts +108 -0
- package/src/auth/sessions.ts +249 -0
- package/src/auth/terminals.ts +284 -0
- package/src/auth.ts +193 -0
- package/src/binding-identity.ts +25 -0
- package/src/bounded-body.ts +35 -0
- package/src/catalog/cs.ts +147 -0
- package/src/catalog/en.ts +148 -0
- package/src/catalog/index.ts +122 -0
- package/src/catalog/uk.ts +164 -0
- package/src/client-address.ts +39 -0
- package/src/common-passwords.ts +37 -0
- package/src/contract-rules.ts +80 -0
- package/src/cron.ts +54 -0
- package/src/db.ts +128 -0
- package/src/delegation.ts +100 -0
- package/src/device-http.ts +39 -0
- package/src/device.ts +269 -0
- package/src/email-identity.ts +2 -0
- package/src/env.ts +132 -0
- package/src/handoff.ts +175 -0
- package/src/html.ts +4 -0
- package/src/human-admission.ts +40 -0
- package/src/identification.ts +185 -0
- package/src/index.ts +292 -0
- package/src/installation-brand.ts +82 -0
- package/src/issue.ts +265 -0
- package/src/json.ts +30 -0
- package/src/log.ts +26 -0
- package/src/membership-http.ts +135 -0
- package/src/membership.ts +1210 -0
- package/src/messages.ts +44 -0
- package/src/narrow-permissions.ts +26 -0
- package/src/node/browser-identity.ts +69 -0
- package/src/node/migrate.ts +52 -0
- package/src/node/prune.ts +34 -0
- package/src/node/runtime.ts +221 -0
- package/src/node/server.ts +104 -0
- package/src/oauth-client-auth.ts +93 -0
- package/src/oauth-client.ts +145 -0
- package/src/oauth-config.ts +72 -0
- package/src/oauth-http.ts +262 -0
- package/src/oauth.ts +272 -0
- package/src/oidc.ts +260 -0
- package/src/origin.ts +29 -0
- package/src/password-crypto.ts +148 -0
- package/src/password-db.ts +419 -0
- package/src/password-minimum.ts +44 -0
- package/src/password-pages.ts +397 -0
- package/src/password-policy.ts +79 -0
- package/src/password-service.ts +67 -0
- package/src/person-locale.ts +103 -0
- package/src/proxy-proof.ts +36 -0
- package/src/relay-mail.ts +64 -0
- package/src/repositories/app-schema.ts +550 -0
- package/src/repositories/audit.ts +405 -0
- package/src/repositories/brand.ts +66 -0
- package/src/repositories/credentials.ts +331 -0
- package/src/repositories/device.ts +137 -0
- package/src/repositories/grants.ts +404 -0
- package/src/repositories/handoff.ts +103 -0
- package/src/repositories/membership-transport.ts +49 -0
- package/src/repositories/membership.ts +875 -0
- package/src/repositories/oauth.ts +122 -0
- package/src/repositories/password-policy.ts +44 -0
- package/src/repositories/principals.ts +358 -0
- package/src/repositories/sessions.ts +339 -0
- package/src/repositories/sql.ts +23 -0
- package/src/repositories/terminals.ts +346 -0
- package/src/repositories/workloads.ts +134 -0
- package/src/request-id.ts +46 -0
- package/src/resolve.ts +396 -0
- package/src/retention.ts +34 -0
- package/src/roles.ts +54 -0
- package/src/rpc-http.ts +333 -0
- package/src/rpc-inputs.ts +110 -0
- package/src/rpc.ts +440 -0
- package/src/secret.ts +45 -0
- package/src/service.ts +59 -0
- package/src/services.ts +199 -0
- package/src/signing.ts +260 -0
- package/src/stored-chain.ts +23 -0
- package/src/stored-permissions.ts +34 -0
- package/src/terminals.ts +15 -0
- package/src/tokens.ts +506 -0
- package/src/workload-token.ts +130 -0
- package/types/fabrika.config.d.ts +11 -0
- package/types/src/admin/access.d.ts +19 -0
- package/types/src/admin/api-keys.d.ts +26 -0
- package/types/src/admin/app-people.d.ts +8 -0
- package/types/src/admin/app-schema.d.ts +32 -0
- package/types/src/admin/audit.d.ts +10 -0
- package/types/src/admin/brand.d.ts +10 -0
- package/types/src/admin/connections.d.ts +5 -0
- package/types/src/admin/context.d.ts +46 -0
- package/types/src/admin/grant-support.d.ts +59 -0
- package/types/src/admin/grants.d.ts +8 -0
- package/types/src/admin/handlers.d.ts +82 -0
- package/types/src/admin/http.d.ts +9 -0
- package/types/src/admin/membership-keys.d.ts +8 -0
- package/types/src/admin/pagination.d.ts +5 -0
- package/types/src/admin/password-policy.d.ts +9 -0
- package/types/src/admin/passwords.d.ts +5 -0
- package/types/src/admin/policies.d.ts +15 -0
- package/types/src/admin/principals.d.ts +15 -0
- package/types/src/admin/router.d.ts +75 -0
- package/types/src/admin/rpc.d.ts +6 -0
- package/types/src/admin/sessions.d.ts +14 -0
- package/types/src/admin/share-links.d.ts +21 -0
- package/types/src/admin/terminals.d.ts +13 -0
- package/types/src/admin/user-admin.d.ts +30 -0
- package/types/src/admin/workloads.d.ts +5 -0
- package/types/src/app-presentation.d.ts +86 -0
- package/types/src/app.d.ts +62 -0
- package/types/src/auth/cookies.d.ts +29 -0
- package/types/src/auth/failure.d.ts +47 -0
- package/types/src/auth/handoff.d.ts +66 -0
- package/types/src/auth/http.d.ts +29 -0
- package/types/src/auth/invitations.d.ts +18 -0
- package/types/src/auth/known-device.d.ts +12 -0
- package/types/src/auth/login.d.ts +10 -0
- package/types/src/auth/oidc-flight.d.ts +39 -0
- package/types/src/auth/oidc.d.ts +7 -0
- package/types/src/auth/password.d.ts +7 -0
- package/types/src/auth/routes.d.ts +15 -0
- package/types/src/auth/sessions.d.ts +60 -0
- package/types/src/auth/terminals.d.ts +47 -0
- package/types/src/auth.d.ts +70 -0
- package/types/src/binding-identity.d.ts +12 -0
- package/types/src/bounded-body.d.ts +12 -0
- package/types/src/catalog/cs.d.ts +2 -0
- package/types/src/catalog/en.d.ts +2 -0
- package/types/src/catalog/index.d.ts +112 -0
- package/types/src/catalog/uk.d.ts +2 -0
- package/types/src/client-address.d.ts +31 -0
- package/types/src/common-passwords.d.ts +2 -0
- package/types/src/contract-rules.d.ts +25 -0
- package/types/src/cron.d.ts +15 -0
- package/types/src/db.d.ts +58 -0
- package/types/src/delegation.d.ts +38 -0
- package/types/src/device-http.d.ts +2 -0
- package/types/src/device.d.ts +11 -0
- package/types/src/email-identity.d.ts +1 -0
- package/types/src/env.d.ts +127 -0
- package/types/src/handoff.d.ts +57 -0
- package/types/src/html.d.ts +2 -0
- package/types/src/human-admission.d.ts +22 -0
- package/types/src/identification.d.ts +30 -0
- package/types/src/index.d.ts +62 -0
- package/types/src/installation-brand.d.ts +22 -0
- package/types/src/issue.d.ts +62 -0
- package/types/src/json.d.ts +15 -0
- package/types/src/log.d.ts +15 -0
- package/types/src/membership-http.d.ts +8 -0
- package/types/src/membership.d.ts +156 -0
- package/types/src/messages.d.ts +20 -0
- package/types/src/narrow-permissions.d.ts +7 -0
- package/types/src/node/browser-identity.d.ts +1 -0
- package/types/src/node/migrate.d.ts +4 -0
- package/types/src/node/prune.d.ts +1 -0
- package/types/src/node/runtime.d.ts +51 -0
- package/types/src/node/server.d.ts +5 -0
- package/types/src/oauth-client-auth.d.ts +26 -0
- package/types/src/oauth-client.d.ts +17 -0
- package/types/src/oauth-config.d.ts +16 -0
- package/types/src/oauth-http.d.ts +7 -0
- package/types/src/oauth.d.ts +51 -0
- package/types/src/oidc.d.ts +81 -0
- package/types/src/origin.d.ts +9 -0
- package/types/src/password-crypto.d.ts +37 -0
- package/types/src/password-db.d.ts +134 -0
- package/types/src/password-minimum.d.ts +23 -0
- package/types/src/password-pages.d.ts +143 -0
- package/types/src/password-policy.d.ts +19 -0
- package/types/src/password-service.d.ts +24 -0
- package/types/src/person-locale.d.ts +50 -0
- package/types/src/proxy-proof.d.ts +21 -0
- package/types/src/relay-mail.d.ts +25 -0
- package/types/src/repositories/app-schema.d.ts +244 -0
- package/types/src/repositories/audit.d.ts +187 -0
- package/types/src/repositories/brand.d.ts +41 -0
- package/types/src/repositories/credentials.d.ts +148 -0
- package/types/src/repositories/device.d.ts +50 -0
- package/types/src/repositories/grants.d.ts +177 -0
- package/types/src/repositories/handoff.d.ts +52 -0
- package/types/src/repositories/membership-transport.d.ts +31 -0
- package/types/src/repositories/membership.d.ts +273 -0
- package/types/src/repositories/oauth.d.ts +55 -0
- package/types/src/repositories/password-policy.d.ts +25 -0
- package/types/src/repositories/principals.d.ts +159 -0
- package/types/src/repositories/sessions.d.ts +150 -0
- package/types/src/repositories/sql.d.ts +13 -0
- package/types/src/repositories/terminals.d.ts +144 -0
- package/types/src/repositories/workloads.d.ts +61 -0
- package/types/src/request-id.d.ts +25 -0
- package/types/src/resolve.d.ts +118 -0
- package/types/src/retention.d.ts +18 -0
- package/types/src/roles.d.ts +34 -0
- package/types/src/rpc-http.d.ts +53 -0
- package/types/src/rpc-inputs.d.ts +707 -0
- package/types/src/rpc.d.ts +4 -0
- package/types/src/secret.d.ts +21 -0
- package/types/src/service.d.ts +19 -0
- package/types/src/services.d.ts +72 -0
- package/types/src/signing.d.ts +72 -0
- package/types/src/stored-chain.d.ts +6 -0
- package/types/src/stored-permissions.d.ts +12 -0
- package/types/src/terminals.d.ts +7 -0
- package/types/src/tokens.d.ts +113 -0
- package/types/src/workload-token.d.ts +7 -0
- package/README.md +0 -3
package/src/oauth.ts
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { buildResourceAccessClaims, DEFAULT_TOKEN_TTL_SECONDS, type KeyGrant, parseOAuthScopes, type PermissionEntry } from '@fabrika/auth-core'
|
|
2
|
+
import type {
|
|
3
|
+
OAuthAuthorizationRequest,
|
|
4
|
+
OAuthClientMetadataDocument,
|
|
5
|
+
OAuthResourceDto,
|
|
6
|
+
OAuthRevocationRequest,
|
|
7
|
+
OAuthTokenRequest,
|
|
8
|
+
OAuthTokenResponse,
|
|
9
|
+
} from '@fabrika/iam-contract'
|
|
10
|
+
import { uuidv7 } from '@fabrika/platform'
|
|
11
|
+
import { sessionUsable } from './auth'
|
|
12
|
+
import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, principalStatus, type SessionRow } from './db'
|
|
13
|
+
import type { Env } from './env'
|
|
14
|
+
import { parseJsonOrNull } from './json'
|
|
15
|
+
import { narrowPermissions } from './narrow-permissions'
|
|
16
|
+
import { clientMetadata } from './oauth-client'
|
|
17
|
+
import type { ManagedOAuthClient, OAuthConfig } from './oauth-config'
|
|
18
|
+
import { pkceChallenge } from './oidc'
|
|
19
|
+
import { unixNow } from './repositories/sql'
|
|
20
|
+
import { authorityDeadline, resolveAuthorityAt } from './resolve'
|
|
21
|
+
import { generateToken, hashToken, timingSafeEqualHex } from './secret'
|
|
22
|
+
import type { Services } from './services'
|
|
23
|
+
import { getSigner, verifyResourceAccessToken } from './signing'
|
|
24
|
+
import { boundedToken } from './tokens'
|
|
25
|
+
|
|
26
|
+
/** An authorization code is redeemed by the client's back end within seconds of the redirect. */
|
|
27
|
+
export const OAUTH_CODE_TTL_SECONDS = 60
|
|
28
|
+
|
|
29
|
+
type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>
|
|
30
|
+
|
|
31
|
+
export interface EstablishedClient {
|
|
32
|
+
registration: ManagedOAuthClient
|
|
33
|
+
metadata: OAuthClientMetadataDocument
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
|
|
38
|
+
* `redirect_uri`. An unregistered client id is refused before any metadata fetch.
|
|
39
|
+
*/
|
|
40
|
+
export async function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null> {
|
|
41
|
+
const registration = config.clients.find((client) => client.clientId === clientId)
|
|
42
|
+
if (registration === undefined || !registration.redirectUris.includes(redirectUri)) return null
|
|
43
|
+
const metadata = await clientMetadata(registration)
|
|
44
|
+
if (metadata === null || !metadata.redirect_uris.includes(redirectUri)) return null
|
|
45
|
+
return { registration, metadata }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Record the consent and return the plaintext authorization code — the only time it exists. */
|
|
49
|
+
export async function grantAuthorization(
|
|
50
|
+
services: Services,
|
|
51
|
+
input: { request: OAuthAuthorizationRequest; resource: OAuthResourceDto; scopes: string[]; session: SessionRow; requestId: string },
|
|
52
|
+
): Promise<string> {
|
|
53
|
+
const now = unixNow()
|
|
54
|
+
const code = generateToken()
|
|
55
|
+
const grantId = uuidv7()
|
|
56
|
+
await services.repositories.oauth.createGrant(
|
|
57
|
+
{
|
|
58
|
+
id: grantId,
|
|
59
|
+
principal_id: input.session.principal_id,
|
|
60
|
+
session_id: input.session.id,
|
|
61
|
+
client_id: input.request.client_id,
|
|
62
|
+
app: input.resource.app,
|
|
63
|
+
resource: input.resource.resource,
|
|
64
|
+
scopes: JSON.stringify(input.scopes),
|
|
65
|
+
created_at: now,
|
|
66
|
+
expires_at: input.session.expires_at,
|
|
67
|
+
revoked_at: null,
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
token_hash: await hashToken(code),
|
|
71
|
+
redirect_uri: input.request.redirect_uri,
|
|
72
|
+
challenge: input.request.code_challenge,
|
|
73
|
+
expires_at: Math.min(now + OAUTH_CODE_TTL_SECONDS, input.session.expires_at),
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
requestId: input.requestId,
|
|
77
|
+
principalId: input.session.principal_id,
|
|
78
|
+
principalLabel: input.session.principal_id,
|
|
79
|
+
app: 'propustka',
|
|
80
|
+
action: 'iam.oauth.grant.create',
|
|
81
|
+
resourceType: 'oauth_grant',
|
|
82
|
+
resourceId: grantId,
|
|
83
|
+
metadata: { clientId: input.request.client_id, app: input.resource.app, resource: input.resource.resource, scopes: input.scopes },
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
return code
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type OAuthTokenOutcome = { ok: true; body: OAuthTokenResponse } | { ok: false; error: 'invalid_grant' }
|
|
90
|
+
|
|
91
|
+
/** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
|
|
92
|
+
export async function exchangeOAuthToken(
|
|
93
|
+
services: Services,
|
|
94
|
+
env: SigningEnv,
|
|
95
|
+
client: EstablishedClient,
|
|
96
|
+
input: OAuthTokenRequest,
|
|
97
|
+
requestId: string,
|
|
98
|
+
): Promise<OAuthTokenOutcome> {
|
|
99
|
+
return input.grant_type === 'authorization_code'
|
|
100
|
+
? redeemCode(services, env, client.metadata, input, requestId)
|
|
101
|
+
: rotateRefreshToken(services, env, client.metadata, input, requestId)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function redeemCode(
|
|
105
|
+
services: Services,
|
|
106
|
+
env: SigningEnv,
|
|
107
|
+
metadata: OAuthClientMetadataDocument,
|
|
108
|
+
input: Extract<OAuthTokenRequest, { grant_type: 'authorization_code' }>,
|
|
109
|
+
requestId: string,
|
|
110
|
+
): Promise<OAuthTokenOutcome> {
|
|
111
|
+
const repository = services.repositories.oauth
|
|
112
|
+
const now = unixNow()
|
|
113
|
+
const hash = await hashToken(input.code)
|
|
114
|
+
// Spent before any comparison, so every presentation of a code is its last — a wrong verifier included.
|
|
115
|
+
const code = await repository.consumeCode(hash, now)
|
|
116
|
+
if (code === null) {
|
|
117
|
+
const spent = await repository.code(hash)
|
|
118
|
+
// A replayed code may mean it leaked; RFC 6749 §4.1.2 says revoke what it issued.
|
|
119
|
+
if (spent !== null) await repository.revokeGrant(spent.grant_id, now, grantRevocation(requestId, spent.grant_id, input.client_id, 'code_replay'))
|
|
120
|
+
return { ok: false, error: 'invalid_grant' }
|
|
121
|
+
}
|
|
122
|
+
const grant = await repository.grant(code.grant_id)
|
|
123
|
+
const proof = timingSafeEqualHex(await hashToken(await pkceChallenge(input.code_verifier)), await hashToken(code.challenge))
|
|
124
|
+
if (
|
|
125
|
+
!proof || code.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource
|
|
126
|
+
|| code.redirect_uri !== input.redirect_uri
|
|
127
|
+
) {
|
|
128
|
+
return { ok: false, error: 'invalid_grant' }
|
|
129
|
+
}
|
|
130
|
+
const access = await mintForGrant(services, env, grant, now)
|
|
131
|
+
if (access === null) return { ok: false, error: 'invalid_grant' }
|
|
132
|
+
if (!metadata.grant_types.includes('refresh_token')) return { ok: true, body: access }
|
|
133
|
+
const refreshToken = generateToken()
|
|
134
|
+
await repository.insertRefreshToken({ token_hash: await hashToken(refreshToken), grant_id: grant.id, expires_at: grant.expires_at })
|
|
135
|
+
return { ok: true, body: { ...access, refresh_token: refreshToken } }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function rotateRefreshToken(
|
|
139
|
+
services: Services,
|
|
140
|
+
env: SigningEnv,
|
|
141
|
+
metadata: OAuthClientMetadataDocument,
|
|
142
|
+
input: Extract<OAuthTokenRequest, { grant_type: 'refresh_token' }>,
|
|
143
|
+
requestId: string,
|
|
144
|
+
): Promise<OAuthTokenOutcome> {
|
|
145
|
+
if (!metadata.grant_types.includes('refresh_token')) return { ok: false, error: 'invalid_grant' }
|
|
146
|
+
const repository = services.repositories.oauth
|
|
147
|
+
const now = unixNow()
|
|
148
|
+
const hash = await hashToken(input.refresh_token)
|
|
149
|
+
const presented = await repository.consumeRefreshToken(hash, now)
|
|
150
|
+
if (presented === null) {
|
|
151
|
+
const spent = await repository.refreshToken(hash)
|
|
152
|
+
// A rotated token presented again: one of the two holders is not the client. The grant is the family.
|
|
153
|
+
if (spent !== null) await repository.revokeGrant(spent.grant_id, now, grantRevocation(requestId, spent.grant_id, input.client_id, 'refresh_replay'))
|
|
154
|
+
return { ok: false, error: 'invalid_grant' }
|
|
155
|
+
}
|
|
156
|
+
const grant = await repository.grant(presented.grant_id)
|
|
157
|
+
if (presented.expires_at <= now || grant === null || grant.client_id !== input.client_id || grant.resource !== input.resource) {
|
|
158
|
+
return { ok: false, error: 'invalid_grant' }
|
|
159
|
+
}
|
|
160
|
+
const access = await mintForGrant(services, env, grant, now)
|
|
161
|
+
if (access === null) return { ok: false, error: 'invalid_grant' }
|
|
162
|
+
const next = generateToken()
|
|
163
|
+
await repository.insertRefreshToken({ token_hash: await hashToken(next), grant_id: grant.id, expires_at: grant.expires_at })
|
|
164
|
+
return { ok: true, body: { ...access, refresh_token: next } }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** RFC 7009: revoking either token kind revokes its grant. An unknown or foreign token is a silent no-op. */
|
|
168
|
+
export async function revokeOAuthToken(services: Services, env: SigningEnv, input: OAuthRevocationRequest, requestId: string): Promise<void> {
|
|
169
|
+
const repository = services.repositories.oauth
|
|
170
|
+
const now = unixNow()
|
|
171
|
+
const refresh = await repository.refreshToken(await hashToken(input.token))
|
|
172
|
+
if (refresh !== null) {
|
|
173
|
+
const grant = await repository.grant(refresh.grant_id)
|
|
174
|
+
if (grant?.client_id === input.client_id) {
|
|
175
|
+
await repository.revokeGrant(grant.id, now, grantRevocation(requestId, grant.id, input.client_id, 'client_revocation'))
|
|
176
|
+
}
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const claims = await verifyResourceAccessToken(await getSigner(env), input.token, { issuer: services.config.issuer })
|
|
180
|
+
if (claims?.oauth === undefined || claims.oauth.clientId !== input.client_id) return
|
|
181
|
+
const grant = await repository.grant(claims.oauth.grantId)
|
|
182
|
+
if (grant !== null && grant.client_id === input.client_id && grant.principal_id === claims.sub) {
|
|
183
|
+
await repository.revokeGrant(grant.id, now, grantRevocation(requestId, grant.id, input.client_id, 'client_revocation'))
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, now: number): Promise<OAuthTokenResponse | null> {
|
|
188
|
+
const authority = await grantAuthority(services, grant, now)
|
|
189
|
+
if (authority === null) return null
|
|
190
|
+
// A replay or a revocation may have landed while authority was resolved; read the grant once more.
|
|
191
|
+
const current = await services.repositories.oauth.grant(grant.id)
|
|
192
|
+
if (current === null || current.revoked_at !== null) return null
|
|
193
|
+
const expiresAt = Math.min(now + DEFAULT_TOKEN_TTL_SECONDS, grant.expires_at, authority.expiresAt ?? Number.POSITIVE_INFINITY)
|
|
194
|
+
const claims = buildResourceAccessClaims({
|
|
195
|
+
iss: services.config.issuer,
|
|
196
|
+
app: grant.app,
|
|
197
|
+
resource: grant.resource,
|
|
198
|
+
subject: authority.principal.id,
|
|
199
|
+
label: authority.principal.label,
|
|
200
|
+
permissions: authority.permissions,
|
|
201
|
+
issuedAt: now,
|
|
202
|
+
expiresAt,
|
|
203
|
+
clientId: grant.client_id,
|
|
204
|
+
scopes: authority.scopes,
|
|
205
|
+
grantId: grant.id,
|
|
206
|
+
tokenId: uuidv7(),
|
|
207
|
+
})
|
|
208
|
+
const token = await boundedToken((await getSigner(env)).signResourceToken(claims), { app: grant.app, subject: authority.principal.id })
|
|
209
|
+
if (token === null) return null
|
|
210
|
+
return {
|
|
211
|
+
access_token: token,
|
|
212
|
+
token_type: 'Bearer',
|
|
213
|
+
expires_in: expiresAt - now,
|
|
214
|
+
scope: authority.scopes.join(' '),
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Everything a grant needs to still mean something, checked at every code exchange and refresh: the
|
|
220
|
+
* grant live, its client and resource still configured, the IAM session it was given under live and
|
|
221
|
+
* usable, the principal an active user. The permissions are resolved live, never from the consent.
|
|
222
|
+
*/
|
|
223
|
+
export async function grantAuthority(
|
|
224
|
+
services: Services,
|
|
225
|
+
grant: OAuthGrantRow,
|
|
226
|
+
now: number,
|
|
227
|
+
): Promise<{ principal: PrincipalRow; scopes: string[]; permissions: PermissionEntry[]; expiresAt: number | null } | null> {
|
|
228
|
+
const config = services.config.oauth
|
|
229
|
+
if (config === null || grant.revoked_at !== null || grant.expires_at <= now) return null
|
|
230
|
+
const resource = config.resources.find((entry) => entry.resource === grant.resource && entry.app === grant.app)
|
|
231
|
+
if (resource === undefined || !config.clients.some((client) => client.clientId === grant.client_id)) return null
|
|
232
|
+
const scopes = parseOAuthScopes(parseJsonOrNull(grant.scopes))
|
|
233
|
+
const ceiling = scopes === null ? null : scopeCeiling(resource, scopes)
|
|
234
|
+
if (scopes === null || ceiling === null) return null
|
|
235
|
+
const session = await services.repositories.sessions.getActiveSessionById(grant.session_id)
|
|
236
|
+
if (session === null || session.app !== null || session.principal_id !== grant.principal_id || !sessionUsable(session, services.config)) return null
|
|
237
|
+
const principal = await services.repositories.principals.getPrincipalById(grant.principal_id)
|
|
238
|
+
if (principal === null || principal.type !== 'user' || principalStatus(principal) !== 'active') return null
|
|
239
|
+
const live = await resolveAuthorityAt(services, principal, grant.app)
|
|
240
|
+
const permissions = narrowPermissions(live.permissions, ceiling)
|
|
241
|
+
return { principal, scopes, permissions, expiresAt: authorityDeadline(live, permissions, now) }
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The union of the scopes' grants, or null when a scope is no longer configured. */
|
|
245
|
+
export function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null {
|
|
246
|
+
const ceiling: KeyGrant[] = []
|
|
247
|
+
for (const scope of scopes) {
|
|
248
|
+
const grant = resource.scopeGrants.find((entry) => entry.scope === scope)
|
|
249
|
+
if (grant === undefined) return null
|
|
250
|
+
ceiling.push(...grant.permissions)
|
|
251
|
+
}
|
|
252
|
+
return ceiling
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
|
|
256
|
+
function grantRevocation(
|
|
257
|
+
requestId: string,
|
|
258
|
+
grantId: string,
|
|
259
|
+
clientId: string,
|
|
260
|
+
reason: 'code_replay' | 'refresh_replay' | 'client_revocation',
|
|
261
|
+
): AuditEventInput {
|
|
262
|
+
return {
|
|
263
|
+
requestId,
|
|
264
|
+
principalId: null,
|
|
265
|
+
principalLabel: 'oauth-client',
|
|
266
|
+
app: 'propustka',
|
|
267
|
+
action: 'iam.oauth.grant.revoke',
|
|
268
|
+
resourceType: 'oauth_grant',
|
|
269
|
+
resourceId: grantId,
|
|
270
|
+
metadata: { clientId, reason },
|
|
271
|
+
}
|
|
272
|
+
}
|
package/src/oidc.ts
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic OIDC relying-party client. IAM federates login to ANY OpenID Connect provider —
|
|
3
|
+
* Google, Auth0, Okta, Keycloak, Microsoft Entra, … — configured purely by env: an `issuer` URL plus
|
|
4
|
+
* a client id/secret. Endpoints are not hardcoded; they come from the provider's discovery document
|
|
5
|
+
* (`${issuer}/.well-known/openid-configuration`), so swapping IdP is a config change, not a code one.
|
|
6
|
+
*
|
|
7
|
+
* 1. `authorizationUrl()` — where the browser logs in (authorization-code + PKCE + state).
|
|
8
|
+
* 2. `exchangeCode()` — swap the returned code (+ PKCE verifier) for an id_token.
|
|
9
|
+
* 3. `verifyIdToken()` — verify it (signature via the discovered JWKS, issuer, audience) and
|
|
10
|
+
* read `sub` + `email`.
|
|
11
|
+
*
|
|
12
|
+
* The discovery document and the JWKS resolver are injectable (the same seam `JwtValidator` uses),
|
|
13
|
+
* so tests run the real protocol logic against a local key with no network. The HTTP route wiring
|
|
14
|
+
* (cookies, redirects) lives in the `auth` handlers; this module is the protocol.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'
|
|
18
|
+
import { z } from 'zod'
|
|
19
|
+
|
|
20
|
+
const tokenResponseSchema = z.object({ id_token: z.string() })
|
|
21
|
+
const identitySchema = z.object({
|
|
22
|
+
sub: z.string(),
|
|
23
|
+
email: z.string(),
|
|
24
|
+
email_verified: z.union([z.boolean(), z.enum(['true', 'false']).transform((value) => value === 'true')]).optional().catch(undefined),
|
|
25
|
+
})
|
|
26
|
+
const metadataSchema = z.object({
|
|
27
|
+
issuer: z.string(),
|
|
28
|
+
authorization_endpoint: z.string(),
|
|
29
|
+
token_endpoint: z.string(),
|
|
30
|
+
jwks_uri: z.string(),
|
|
31
|
+
}).transform((value) => ({
|
|
32
|
+
issuer: value.issuer,
|
|
33
|
+
authorizationEndpoint: value.authorization_endpoint,
|
|
34
|
+
tokenEndpoint: value.token_endpoint,
|
|
35
|
+
jwksUri: value.jwks_uri,
|
|
36
|
+
}))
|
|
37
|
+
|
|
38
|
+
export interface OidcConfig {
|
|
39
|
+
/** The provider's issuer URL — the discovery base AND the `iss` an id_token must carry. */
|
|
40
|
+
issuer: string
|
|
41
|
+
clientId: string
|
|
42
|
+
clientSecret: string
|
|
43
|
+
/** Absolute callback URL — `${ISSUER}/auth/callback`. Must be registered with the provider. */
|
|
44
|
+
redirectUri: string
|
|
45
|
+
/** Space-separated scopes; defaults to `openid email profile` when empty. `openid` + `email` are required. */
|
|
46
|
+
scopes: string
|
|
47
|
+
/** Reject a login whose `email_verified` is not true. Default true; an IdP that omits the claim needs false. */
|
|
48
|
+
requireVerifiedEmail: boolean
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The verified upstream identity we resolve a principal from. */
|
|
52
|
+
export interface OidcIdentity {
|
|
53
|
+
/** The IdP `sub` — the stable upstream subject, stored as the principal's `external_id`. */
|
|
54
|
+
sub: string
|
|
55
|
+
email: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The subset of the OIDC discovery document IAM needs. */
|
|
59
|
+
export interface OidcMetadata {
|
|
60
|
+
issuer: string
|
|
61
|
+
authorizationEndpoint: string
|
|
62
|
+
tokenEndpoint: string
|
|
63
|
+
jwksUri: string
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Injectable seams for tests: a fixed discovery doc and/or a local JWKS resolver (no network). */
|
|
67
|
+
export interface OidcDeps {
|
|
68
|
+
metadata?: OidcMetadata
|
|
69
|
+
jwks?: JWTVerifyGetKey
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── PKCE ────────────────────────────────────────────────────────────────────────
|
|
73
|
+
|
|
74
|
+
/** URL-safe base64 of raw bytes (no padding) — the PKCE encoding. */
|
|
75
|
+
function base64url(bytes: Uint8Array): string {
|
|
76
|
+
let binary = ''
|
|
77
|
+
for (const b of bytes) {
|
|
78
|
+
binary += String.fromCharCode(b)
|
|
79
|
+
}
|
|
80
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** A random URL-safe token (default 32 bytes / 256 bits) — PKCE verifier, state nonce, session id. */
|
|
84
|
+
export function randomToken(bytes = 32): string {
|
|
85
|
+
const buf = new Uint8Array(bytes)
|
|
86
|
+
crypto.getRandomValues(buf)
|
|
87
|
+
return base64url(buf)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Generate a PKCE pair: a high-entropy `verifier` and its S256 `challenge`. */
|
|
91
|
+
export async function generatePkce(): Promise<{ verifier: string; challenge: string }> {
|
|
92
|
+
const verifier = randomToken(32)
|
|
93
|
+
return { verifier, challenge: await pkceChallenge(verifier) }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Derive an S256 challenge from a browser-held verifier. */
|
|
97
|
+
export async function pkceChallenge(verifier: string): Promise<string> {
|
|
98
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))
|
|
99
|
+
return base64url(new Uint8Array(digest))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── The client ───────────────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
export class OidcClient {
|
|
105
|
+
constructor(
|
|
106
|
+
private readonly config: OidcConfig,
|
|
107
|
+
private readonly deps: OidcDeps = {},
|
|
108
|
+
) {}
|
|
109
|
+
|
|
110
|
+
/** Where to send the browser to log in. `state` is the CSRF token; `codeChallenge` is the PKCE S256. */
|
|
111
|
+
async authorizationUrl(params: { state: string; codeChallenge: string }): Promise<string> {
|
|
112
|
+
const meta = await this.metadata()
|
|
113
|
+
const url = new URL(meta.authorizationEndpoint)
|
|
114
|
+
url.searchParams.set('client_id', this.config.clientId)
|
|
115
|
+
url.searchParams.set('redirect_uri', this.config.redirectUri)
|
|
116
|
+
url.searchParams.set('response_type', 'code')
|
|
117
|
+
url.searchParams.set('scope', this.scopes())
|
|
118
|
+
url.searchParams.set('state', params.state)
|
|
119
|
+
url.searchParams.set('code_challenge', params.codeChallenge)
|
|
120
|
+
url.searchParams.set('code_challenge_method', 'S256')
|
|
121
|
+
return url.toString()
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Exchange an authorization `code` (+ the PKCE `verifier`) for an id_token at the provider's
|
|
126
|
+
* token endpoint. Returns the raw id_token, or null on any failure (caller treats as auth failure).
|
|
127
|
+
*/
|
|
128
|
+
async exchangeCode(code: string, codeVerifier: string): Promise<string | null> {
|
|
129
|
+
const meta = await this.metadata()
|
|
130
|
+
const response = await fetch(meta.tokenEndpoint, {
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
133
|
+
body: this.tokenRequestBody(code, codeVerifier).toString(),
|
|
134
|
+
// The body holds the client secret: a followed 307/308 would send it again to wherever it points.
|
|
135
|
+
redirect: 'manual',
|
|
136
|
+
})
|
|
137
|
+
if (!response.ok) {
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
const json: unknown = await response.json().catch(() => null)
|
|
141
|
+
const parsed = tokenResponseSchema.safeParse(json)
|
|
142
|
+
return parsed.success ? parsed.data.id_token : null
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The x-www-form-urlencoded body for the code→token exchange (separated so it's unit-testable). */
|
|
146
|
+
tokenRequestBody(code: string, codeVerifier: string): URLSearchParams {
|
|
147
|
+
return new URLSearchParams({
|
|
148
|
+
grant_type: 'authorization_code',
|
|
149
|
+
code,
|
|
150
|
+
client_id: this.config.clientId,
|
|
151
|
+
client_secret: this.config.clientSecret,
|
|
152
|
+
redirect_uri: this.config.redirectUri,
|
|
153
|
+
code_verifier: codeVerifier,
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Verify an id_token (signature against the discovered JWKS, issuer, audience) and extract the
|
|
159
|
+
* identity. Honors `requireVerifiedEmail`. Returns null on any problem — never throws.
|
|
160
|
+
*/
|
|
161
|
+
async verifyIdToken(idToken: string): Promise<OidcIdentity | null> {
|
|
162
|
+
let meta: OidcMetadata
|
|
163
|
+
try {
|
|
164
|
+
meta = await this.metadata()
|
|
165
|
+
} catch {
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
let payload: unknown
|
|
169
|
+
try {
|
|
170
|
+
const result = await jwtVerify(idToken, this.jwksResolver(meta), {
|
|
171
|
+
issuer: meta.issuer,
|
|
172
|
+
audience: this.config.clientId,
|
|
173
|
+
})
|
|
174
|
+
payload = result.payload
|
|
175
|
+
} catch {
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
const identity = identitySchema.safeParse(payload)
|
|
179
|
+
if (!identity.success) {
|
|
180
|
+
return null
|
|
181
|
+
}
|
|
182
|
+
const { sub, email, email_verified: verified } = identity.data
|
|
183
|
+
// require=true → must be explicitly verified; require=false → only an EXPLICIT false is refused.
|
|
184
|
+
if (this.config.requireVerifiedEmail ? verified !== true : verified === false) {
|
|
185
|
+
return null
|
|
186
|
+
}
|
|
187
|
+
return { sub, email }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private scopes(): string {
|
|
191
|
+
return this.config.scopes.trim() === '' ? 'openid email profile' : this.config.scopes
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The provider's discovery metadata — injected (tests), else fetched once per isolate and cached. */
|
|
195
|
+
async metadata(): Promise<OidcMetadata> {
|
|
196
|
+
if (this.deps.metadata) {
|
|
197
|
+
return this.deps.metadata
|
|
198
|
+
}
|
|
199
|
+
const now = Date.now() / 1000
|
|
200
|
+
const cached = metadataCache.get(this.config.issuer)
|
|
201
|
+
if (cached && cached.expiresAt > now) {
|
|
202
|
+
return cached.metadata
|
|
203
|
+
}
|
|
204
|
+
const url = `${this.config.issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`
|
|
205
|
+
// Never follow a redirect: the document picks the endpoint that receives the client secret and the
|
|
206
|
+
// keys that vouch for identities, and the issuer check below cannot tell an echoed issuer apart.
|
|
207
|
+
const response = await fetch(url, { redirect: 'manual' })
|
|
208
|
+
if (!response.ok) {
|
|
209
|
+
throw new Error(discoveryFailure(this.config.issuer, url, response))
|
|
210
|
+
}
|
|
211
|
+
const metadata = parseMetadata(await response.json().catch(() => null))
|
|
212
|
+
if (!metadata) {
|
|
213
|
+
throw new Error(`OIDC discovery document at ${url} is missing required fields`)
|
|
214
|
+
}
|
|
215
|
+
// Per the OIDC spec the document's issuer MUST equal the issuer used to fetch it (anti-spoofing).
|
|
216
|
+
if (metadata.issuer !== this.config.issuer) {
|
|
217
|
+
throw new Error(`OIDC issuer mismatch: configured ${this.config.issuer}, discovered ${metadata.issuer}`)
|
|
218
|
+
}
|
|
219
|
+
metadataCache.set(this.config.issuer, { metadata, expiresAt: now + METADATA_TTL_SECONDS })
|
|
220
|
+
return metadata
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
private jwksResolver(meta: OidcMetadata): JWTVerifyGetKey {
|
|
224
|
+
if (this.deps.jwks) {
|
|
225
|
+
return this.deps.jwks
|
|
226
|
+
}
|
|
227
|
+
let resolver = jwksResolvers.get(meta.jwksUri)
|
|
228
|
+
if (!resolver) {
|
|
229
|
+
resolver = createRemoteJWKSet(new URL(meta.jwksUri))
|
|
230
|
+
jwksResolvers.set(meta.jwksUri, resolver)
|
|
231
|
+
}
|
|
232
|
+
return resolver
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Why discovery failed. A redirect names only the origin it points to, never its path or query, and says what to change:
|
|
238
|
+
* the issuer must be the URL whose own discovery document answers.
|
|
239
|
+
*/
|
|
240
|
+
function discoveryFailure(issuer: string, url: string, response: Response): string {
|
|
241
|
+
if (response.type !== 'opaqueredirect' && (response.status < 300 || response.status >= 400)) {
|
|
242
|
+
return `OIDC discovery failed for ${issuer}: ${response.status}`
|
|
243
|
+
}
|
|
244
|
+
const location = response.headers.get('location')
|
|
245
|
+
const target = location !== null && URL.canParse(location, url) ? ` to ${new URL(location, url).origin}` : ''
|
|
246
|
+
return `OIDC discovery failed for ${issuer}: ${response.status}, a redirect${target}, which is not followed; `
|
|
247
|
+
+ 'configure the issuer exactly as the provider publishes it, so its /.well-known/openid-configuration answers directly'
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ── Discovery + JWKS caches (per isolate) ──────────────────────────────────────────
|
|
251
|
+
|
|
252
|
+
const METADATA_TTL_SECONDS = 3600
|
|
253
|
+
const metadataCache = new Map<string, { metadata: OidcMetadata; expiresAt: number }>()
|
|
254
|
+
/** One remote JWKS resolver per jwks_uri (jose caches the fetched keys on it). */
|
|
255
|
+
const jwksResolvers = new Map<string, JWTVerifyGetKey>()
|
|
256
|
+
|
|
257
|
+
function parseMetadata(doc: unknown): OidcMetadata | null {
|
|
258
|
+
const parsed = metadataSchema.safeParse(doc)
|
|
259
|
+
return parsed.success ? parsed.data : null
|
|
260
|
+
}
|
package/src/origin.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** One canonical spelling for an HTTP origin, shared by everything in IAM that compares one. */
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A canonical origin can be written into a CSP source list as it is: a host name, an IPv4 or a bracketed IPv6
|
|
5
|
+
* address, and a port. The URL parser keeps `;`, `,`, quotes and `*` in a host, and each of those would end or widen
|
|
6
|
+
* the `form-action` directive the origin is written into.
|
|
7
|
+
*/
|
|
8
|
+
const CSP_SAFE_ORIGIN = /^https?:\/\/(?:[a-z0-9._-]+|\[[0-9a-f:.]+\])(?::[0-9]+)?$/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Canonical origin: lower-cased scheme and host, explicit port only when non-default, no path. Both
|
|
12
|
+
* sides of a comparison go through here, so `https://App.example.com:443/` and
|
|
13
|
+
* `https://app.example.com` are the same origin and neither side has to remember which spelling was
|
|
14
|
+
* registered. Returns null for anything that is not an absolute http(s) URL, and for a host carrying
|
|
15
|
+
* a character a CSP source cannot hold (`CSP_SAFE_ORIGIN`).
|
|
16
|
+
*/
|
|
17
|
+
export function normalizeOrigin(value: string): string | null {
|
|
18
|
+
let url: URL
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(value)
|
|
21
|
+
} catch {
|
|
22
|
+
return null
|
|
23
|
+
}
|
|
24
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
25
|
+
return null
|
|
26
|
+
}
|
|
27
|
+
const origin = url.origin.toLowerCase()
|
|
28
|
+
return CSP_SAFE_ORIGIN.test(origin) ? origin : null
|
|
29
|
+
}
|