@adonis-agora/authkit-poppy 0.0.0-stage → 0.3.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 +9 -0
- package/LICENSE +21 -0
- package/README.md +40 -2
- package/build/configure.d.ts +3 -0
- package/build/configure.js +43 -0
- package/build/index.d.ts +20 -0
- package/build/index.js +18 -0
- package/build/src/augmentations.d.ts +1 -0
- package/build/src/augmentations.js +1 -0
- package/build/src/client_registry.d.ts +50 -0
- package/build/src/client_registry.js +260 -0
- package/build/src/config.d.ts +396 -0
- package/build/src/config.js +228 -0
- package/build/src/controllers/poppy_consent_controller.d.ts +19 -0
- package/build/src/controllers/poppy_consent_controller.js +194 -0
- package/build/src/controllers/poppy_controller.d.ts +33 -0
- package/build/src/controllers/poppy_controller.js +219 -0
- package/build/src/dpop.d.ts +61 -0
- package/build/src/dpop.js +158 -0
- package/build/src/email_code_sign_in.d.ts +40 -0
- package/build/src/email_code_sign_in.js +142 -0
- package/build/src/errors.d.ts +25 -0
- package/build/src/errors.js +25 -0
- package/build/src/extension.d.ts +37 -0
- package/build/src/extension.js +167 -0
- package/build/src/messages.d.ts +20 -0
- package/build/src/messages.js +22 -0
- package/build/src/redirect_exact.d.ts +6 -0
- package/build/src/redirect_exact.js +11 -0
- package/build/src/replay.d.ts +25 -0
- package/build/src/replay.js +106 -0
- package/build/src/resource.d.ts +100 -0
- package/build/src/resource.js +122 -0
- package/build/src/runtime.d.ts +8 -0
- package/build/src/runtime.js +15 -0
- package/build/src/safe_fetch.d.ts +48 -0
- package/build/src/safe_fetch.js +262 -0
- package/build/src/service.d.ts +301 -0
- package/build/src/service.js +1488 -0
- package/build/src/session_jwt.d.ts +30 -0
- package/build/src/session_jwt.js +133 -0
- package/build/src/store.d.ts +106 -0
- package/build/src/store.js +261 -0
- package/build/src/tables.d.ts +27 -0
- package/build/src/tables.js +156 -0
- package/build/src/web_session.d.ts +43 -0
- package/build/src/web_session.js +120 -0
- package/package.json +70 -3
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import '../augmentations.js';
|
|
2
|
+
import { ACCOUNT_SESSION_KEY, impersonationState, } from '@adonis-agora/authkit-server';
|
|
3
|
+
import { redirectExact } from '../redirect_exact.js';
|
|
4
|
+
import { poppyFor } from '../runtime.js';
|
|
5
|
+
/** A tela nunca pode ser emoldurada (clickjacking — como a do PACT no authkit-server). */
|
|
6
|
+
function denyFraming(ctx) {
|
|
7
|
+
ctx.response.header('X-Frame-Options', 'DENY');
|
|
8
|
+
ctx.response.header('Content-Security-Policy', "frame-ancestors 'none'");
|
|
9
|
+
}
|
|
10
|
+
function chosenScopes(ctx) {
|
|
11
|
+
const raw = ctx.request.input('scope');
|
|
12
|
+
return (Array.isArray(raw) ? raw : raw ? [raw] : []).map(String);
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Telas do usuário no Poppy: o consentimento do Direct Sign-In (o
|
|
16
|
+
* `authorization_endpoint`, §4.2) e a do Device Sign-In (o `verification_uri`,
|
|
17
|
+
* §4.3). Montadas atrás do `accountGuard`: sem sessão, o usuário passa pelo login
|
|
18
|
+
* DESTE app e volta. Abrir o link nunca aprova sozinho — a aprovação é um POST
|
|
19
|
+
* com CSRF. Recusadas durante impersonation.
|
|
20
|
+
*/
|
|
21
|
+
export default class PoppyConsentController {
|
|
22
|
+
/** GET {prefix}/oauth/authorize */
|
|
23
|
+
async authorize(ctx) {
|
|
24
|
+
const poppy = await poppyFor(ctx);
|
|
25
|
+
if (!poppy?.cfg.signIn.direct)
|
|
26
|
+
return ctx.response.notFound();
|
|
27
|
+
denyFraming(ctx);
|
|
28
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
29
|
+
const render = service.config.render;
|
|
30
|
+
if (impersonationState(ctx).active) {
|
|
31
|
+
return render(ctx, 'agents/consent', {
|
|
32
|
+
csrfToken: ctx.request.csrfToken,
|
|
33
|
+
action: poppy.urls.authorization,
|
|
34
|
+
request: null,
|
|
35
|
+
account: null,
|
|
36
|
+
error: 'agents.consent.impersonating',
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
const accountId = ctx.session.get(ACCOUNT_SESSION_KEY);
|
|
40
|
+
const outcome = await poppy.startAuthorization(ctx.request.qs(), accountId);
|
|
41
|
+
if (outcome.kind === 'redirect')
|
|
42
|
+
return redirectExact(ctx.response, outcome.url);
|
|
43
|
+
if (outcome.kind === 'error') {
|
|
44
|
+
ctx.response.status(400);
|
|
45
|
+
return render(ctx, 'agents/done', {
|
|
46
|
+
status: 'invalid',
|
|
47
|
+
agentName: null,
|
|
48
|
+
scopes: [],
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const account = await service.config.accountStore.findById(accountId);
|
|
52
|
+
return render(ctx, 'agents/consent', {
|
|
53
|
+
csrfToken: ctx.request.csrfToken,
|
|
54
|
+
action: poppy.urls.authorization,
|
|
55
|
+
request: {
|
|
56
|
+
agentName: outcome.request.agentName,
|
|
57
|
+
agentOrigin: outcome.request.agentOrigin,
|
|
58
|
+
logoUri: outcome.request.logoUri,
|
|
59
|
+
scopes: outcome.request.scopes,
|
|
60
|
+
hidden: [{ name: 'request_id', value: outcome.request.id }],
|
|
61
|
+
},
|
|
62
|
+
account: { email: account?.email ?? null },
|
|
63
|
+
error: null,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** POST {prefix}/oauth/authorize — `request_id`, `decision=allow|deny`, `scope[]`. */
|
|
67
|
+
async decideAuthorization(ctx) {
|
|
68
|
+
const poppy = await poppyFor(ctx);
|
|
69
|
+
if (!poppy?.cfg.signIn.direct)
|
|
70
|
+
return ctx.response.notFound();
|
|
71
|
+
denyFraming(ctx);
|
|
72
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
73
|
+
const cfg = service.config;
|
|
74
|
+
const render = cfg.render;
|
|
75
|
+
if (impersonationState(ctx).active) {
|
|
76
|
+
return render(ctx, 'agents/done', {
|
|
77
|
+
status: 'expired',
|
|
78
|
+
agentName: null,
|
|
79
|
+
scopes: [],
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
const accountId = ctx.session.get(ACCOUNT_SESSION_KEY);
|
|
83
|
+
const decided = await poppy.decideAuthorization({
|
|
84
|
+
requestId: String(ctx.request.input('request_id') ?? ''),
|
|
85
|
+
accountId,
|
|
86
|
+
allow: ctx.request.input('decision') === 'allow',
|
|
87
|
+
scopes: chosenScopes(ctx),
|
|
88
|
+
});
|
|
89
|
+
if (!decided) {
|
|
90
|
+
return render(ctx, 'agents/done', {
|
|
91
|
+
status: 'expired',
|
|
92
|
+
agentName: null,
|
|
93
|
+
scopes: [],
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
await cfg.audit?.record({
|
|
97
|
+
type: decided.approved ? 'agent.delegation_approved' : 'agent.delegation_denied',
|
|
98
|
+
accountId,
|
|
99
|
+
clientId: decided.clientId,
|
|
100
|
+
ip: ctx.request.ip?.() ?? null,
|
|
101
|
+
metadata: { protocol: 'poppy', signIn: 'direct', scopes: decided.approved ?? [] },
|
|
102
|
+
});
|
|
103
|
+
return redirectExact(ctx.response, decided.url);
|
|
104
|
+
}
|
|
105
|
+
/** GET {prefix}/device?user_code=XXXX-XXXX */
|
|
106
|
+
async device(ctx) {
|
|
107
|
+
const poppy = await poppyFor(ctx);
|
|
108
|
+
if (!poppy?.cfg.signIn.device)
|
|
109
|
+
return ctx.response.notFound();
|
|
110
|
+
denyFraming(ctx);
|
|
111
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
112
|
+
const render = service.config.render;
|
|
113
|
+
const base = {
|
|
114
|
+
csrfToken: ctx.request.csrfToken,
|
|
115
|
+
action: poppy.urls.device,
|
|
116
|
+
request: null,
|
|
117
|
+
account: null,
|
|
118
|
+
error: null,
|
|
119
|
+
};
|
|
120
|
+
if (impersonationState(ctx).active) {
|
|
121
|
+
return render(ctx, 'agents/consent', {
|
|
122
|
+
...base,
|
|
123
|
+
error: 'agents.consent.impersonating',
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
const input = ctx.request.input('user_code');
|
|
127
|
+
if (!input)
|
|
128
|
+
return render(ctx, 'agents/consent', base);
|
|
129
|
+
const pending = await poppy.pendingDevice(input);
|
|
130
|
+
if (!pending) {
|
|
131
|
+
return render(ctx, 'agents/consent', {
|
|
132
|
+
...base,
|
|
133
|
+
error: 'agents.consent.invalid_code',
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
const accountId = ctx.session.get(ACCOUNT_SESSION_KEY);
|
|
137
|
+
const account = await service.config.accountStore.findById(accountId);
|
|
138
|
+
return render(ctx, 'agents/consent', {
|
|
139
|
+
...base,
|
|
140
|
+
request: {
|
|
141
|
+
userCode: pending.userCode,
|
|
142
|
+
agentName: pending.agentName,
|
|
143
|
+
agentOrigin: pending.agentOrigin,
|
|
144
|
+
scopes: pending.scopes,
|
|
145
|
+
},
|
|
146
|
+
account: { email: account?.email ?? null },
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
/** POST {prefix}/device — `user_code`, `decision`, `scope[]`. */
|
|
150
|
+
async decideDevice(ctx) {
|
|
151
|
+
const poppy = await poppyFor(ctx);
|
|
152
|
+
if (!poppy?.cfg.signIn.device)
|
|
153
|
+
return ctx.response.notFound();
|
|
154
|
+
denyFraming(ctx);
|
|
155
|
+
const service = await ctx.containerResolver.make('authkit.server');
|
|
156
|
+
const cfg = service.config;
|
|
157
|
+
const render = cfg.render;
|
|
158
|
+
if (impersonationState(ctx).active) {
|
|
159
|
+
return render(ctx, 'agents/done', {
|
|
160
|
+
status: 'expired',
|
|
161
|
+
agentName: null,
|
|
162
|
+
scopes: [],
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
const accountId = ctx.session.get(ACCOUNT_SESSION_KEY);
|
|
166
|
+
const userCode = String(ctx.request.input('user_code') ?? '');
|
|
167
|
+
const pending = await poppy.pendingDevice(userCode);
|
|
168
|
+
const decided = await poppy.decideDevice({
|
|
169
|
+
userCode,
|
|
170
|
+
accountId,
|
|
171
|
+
allow: ctx.request.input('decision') === 'allow',
|
|
172
|
+
scopes: chosenScopes(ctx),
|
|
173
|
+
});
|
|
174
|
+
if (!decided || !pending) {
|
|
175
|
+
return render(ctx, 'agents/done', {
|
|
176
|
+
status: 'expired',
|
|
177
|
+
agentName: null,
|
|
178
|
+
scopes: [],
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
await cfg.audit?.record({
|
|
182
|
+
type: decided.approved ? 'agent.delegation_approved' : 'agent.delegation_denied',
|
|
183
|
+
accountId,
|
|
184
|
+
clientId: decided.clientId,
|
|
185
|
+
ip: ctx.request.ip?.() ?? null,
|
|
186
|
+
metadata: { protocol: 'poppy', signIn: 'device', scopes: decided.approved ?? [] },
|
|
187
|
+
});
|
|
188
|
+
return render(ctx, 'agents/done', {
|
|
189
|
+
status: decided.approved ? 'approved' : 'denied',
|
|
190
|
+
agentName: pending.agentName,
|
|
191
|
+
scopes: decided.approved ? poppy.describe(decided.approved) : [],
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { HttpContext } from '@adonisjs/core/http';
|
|
2
|
+
/**
|
|
3
|
+
* Endpoints do Poppy (§3, §4, §6): descoberta, protected resource metadata, metadata RFC 8414,
|
|
4
|
+
* token, revogação, device authorization e a entrada do navegador na Session. Os POSTs são isentos
|
|
5
|
+
* de CSRF — `csrfExemptPaths` da extension, que o `authkitCsrfExceptions` do authkit lê.
|
|
6
|
+
*/
|
|
7
|
+
export default class PoppyController {
|
|
8
|
+
/** `GET /.well-known/poppy.json` — só no domínio da empresa; `www.` redireciona para ele. */
|
|
9
|
+
discovery(ctx: HttpContext): Promise<void>;
|
|
10
|
+
/** `GET /.well-known/oauth-protected-resource` do domínio (§3.2, RFC 9728). */
|
|
11
|
+
protectedResource(ctx: HttpContext): Promise<void>;
|
|
12
|
+
/** `GET /.well-known/oauth-authorization-server{prefix}` (RFC 8414 + `protected_resources`). */
|
|
13
|
+
metadata(ctx: HttpContext): Promise<void>;
|
|
14
|
+
token(ctx: HttpContext): Promise<void>;
|
|
15
|
+
deviceAuthorization(ctx: HttpContext): Promise<void>;
|
|
16
|
+
/** RFC 7009: 200 também para token desconhecido. */
|
|
17
|
+
revoke(ctx: HttpContext): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* `GET web.browser_session_endpoint` (§6, passo 1): a página com o código de uso único e o cookie
|
|
20
|
+
* que o prende a este navegador. Não mexe em Session nem nos outros cookies.
|
|
21
|
+
*/
|
|
22
|
+
browserSessionPage(ctx: HttpContext): Promise<void>;
|
|
23
|
+
/**
|
|
24
|
+
* `POST {browser_session_endpoint}/authorize` (§6, passo 2): o agente autoriza o código, com o
|
|
25
|
+
* header da Session e, se logado, o access token. 204; código inválido → 400 `invalid_request`.
|
|
26
|
+
*/
|
|
27
|
+
browserSessionAuthorize(ctx: HttpContext): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* `POST web.browser_session_endpoint` (§6, passo 3): o navegador submete o código → cookie do app
|
|
30
|
+
* para a Session, limpa o cookie do passo 1 e redireciona para o site; falha → página de erro.
|
|
31
|
+
*/
|
|
32
|
+
browserSession(ctx: HttpContext): Promise<void>;
|
|
33
|
+
}
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { PoppyError } from '../errors.js';
|
|
2
|
+
import { publicRequestUrl, writePoppyAuthError } from '../resource.js';
|
|
3
|
+
import { poppyFor } from '../runtime.js';
|
|
4
|
+
import { loginPoppyBrowser } from '../web_session.js';
|
|
5
|
+
function noStore(ctx) {
|
|
6
|
+
ctx.response.header('Cache-Control', 'no-store');
|
|
7
|
+
ctx.response.header('Pragma', 'no-cache');
|
|
8
|
+
}
|
|
9
|
+
function withNonce(ctx, poppy) {
|
|
10
|
+
const nonce = poppy.nonce();
|
|
11
|
+
if (nonce)
|
|
12
|
+
ctx.response.header('DPoP-Nonce', nonce);
|
|
13
|
+
}
|
|
14
|
+
function oauthError(ctx, error) {
|
|
15
|
+
noStore(ctx);
|
|
16
|
+
for (const [k, v] of Object.entries(error.headers))
|
|
17
|
+
ctx.response.header(k, v);
|
|
18
|
+
// Limite de taxa: 429 com `Retry-After`, sem corpo próprio (§5.6).
|
|
19
|
+
if (error.status === 429)
|
|
20
|
+
return ctx.response.status(429).send('');
|
|
21
|
+
if (error.code === 'invalid_dpop_proof' || error.code === 'use_dpop_nonce') {
|
|
22
|
+
ctx.response.header('WWW-Authenticate', `DPoP error="${error.code}"`);
|
|
23
|
+
}
|
|
24
|
+
return ctx.response.status(error.status).json(error.toJSON());
|
|
25
|
+
}
|
|
26
|
+
async function poppyOr404(ctx) {
|
|
27
|
+
const poppy = await poppyFor(ctx);
|
|
28
|
+
if (!poppy)
|
|
29
|
+
ctx.response.notFound();
|
|
30
|
+
return poppy;
|
|
31
|
+
}
|
|
32
|
+
/** Formulário (`application/x-www-form-urlencoded`) da request. */
|
|
33
|
+
function form(ctx) {
|
|
34
|
+
return ctx.request.all();
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Endpoints do Poppy (§3, §4, §6): descoberta, protected resource metadata, metadata RFC 8414,
|
|
38
|
+
* token, revogação, device authorization e a entrada do navegador na Session. Os POSTs são isentos
|
|
39
|
+
* de CSRF — `csrfExemptPaths` da extension, que o `authkitCsrfExceptions` do authkit lê.
|
|
40
|
+
*/
|
|
41
|
+
export default class PoppyController {
|
|
42
|
+
/** `GET /.well-known/poppy.json` — só no domínio da empresa; `www.` redireciona para ele. */
|
|
43
|
+
async discovery(ctx) {
|
|
44
|
+
const poppy = await poppyOr404(ctx);
|
|
45
|
+
if (!poppy)
|
|
46
|
+
return;
|
|
47
|
+
// `host()` mantém a porta (dev em `localhost:3333`): o `browser_session_endpoint` sai dele.
|
|
48
|
+
const host = ctx.request.host() ?? ctx.request.hostname() ?? '';
|
|
49
|
+
const redirect = poppy.discoveryRedirect(host);
|
|
50
|
+
if (redirect) {
|
|
51
|
+
ctx.response.header('Location', redirect);
|
|
52
|
+
return ctx.response.status(308).send('');
|
|
53
|
+
}
|
|
54
|
+
const doc = poppy.discoveryDocument(host);
|
|
55
|
+
if (!doc)
|
|
56
|
+
return ctx.response.notFound();
|
|
57
|
+
ctx.response.header('Access-Control-Allow-Origin', '*');
|
|
58
|
+
ctx.response.header('Cache-Control', 'public, max-age=300');
|
|
59
|
+
return ctx.response.json(doc);
|
|
60
|
+
}
|
|
61
|
+
/** `GET /.well-known/oauth-protected-resource` do domínio (§3.2, RFC 9728). */
|
|
62
|
+
async protectedResource(ctx) {
|
|
63
|
+
const poppy = await poppyOr404(ctx);
|
|
64
|
+
if (!poppy)
|
|
65
|
+
return;
|
|
66
|
+
const doc = poppy.protectedResourceMetadata(ctx.request.host() ?? ctx.request.hostname() ?? '');
|
|
67
|
+
if (!doc)
|
|
68
|
+
return ctx.response.notFound();
|
|
69
|
+
ctx.response.header('Access-Control-Allow-Origin', '*');
|
|
70
|
+
ctx.response.header('Cache-Control', 'public, max-age=300');
|
|
71
|
+
return ctx.response.json(doc);
|
|
72
|
+
}
|
|
73
|
+
/** `GET /.well-known/oauth-authorization-server{prefix}` (RFC 8414 + `protected_resources`). */
|
|
74
|
+
async metadata(ctx) {
|
|
75
|
+
const poppy = await poppyOr404(ctx);
|
|
76
|
+
if (!poppy)
|
|
77
|
+
return;
|
|
78
|
+
ctx.response.header('Access-Control-Allow-Origin', '*');
|
|
79
|
+
ctx.response.header('Cache-Control', 'public, max-age=300');
|
|
80
|
+
return ctx.response.json(poppy.authorizationServerMetadata());
|
|
81
|
+
}
|
|
82
|
+
async token(ctx) {
|
|
83
|
+
const poppy = await poppyOr404(ctx);
|
|
84
|
+
if (!poppy)
|
|
85
|
+
return;
|
|
86
|
+
withNonce(ctx, poppy);
|
|
87
|
+
try {
|
|
88
|
+
const body = await poppy.token(form(ctx), ctx.request.header('dpop'), ctx);
|
|
89
|
+
noStore(ctx);
|
|
90
|
+
return ctx.response.json(body);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof PoppyError)
|
|
94
|
+
return oauthError(ctx, error);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async deviceAuthorization(ctx) {
|
|
99
|
+
const poppy = await poppyOr404(ctx);
|
|
100
|
+
if (!poppy)
|
|
101
|
+
return;
|
|
102
|
+
try {
|
|
103
|
+
const body = await poppy.deviceAuthorization(form(ctx));
|
|
104
|
+
noStore(ctx);
|
|
105
|
+
return ctx.response.json(body);
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (error instanceof PoppyError)
|
|
109
|
+
return oauthError(ctx, error);
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** RFC 7009: 200 também para token desconhecido. */
|
|
114
|
+
async revoke(ctx) {
|
|
115
|
+
const poppy = await poppyOr404(ctx);
|
|
116
|
+
if (!poppy)
|
|
117
|
+
return;
|
|
118
|
+
try {
|
|
119
|
+
await poppy.revoke(form(ctx));
|
|
120
|
+
noStore(ctx);
|
|
121
|
+
return ctx.response.status(200).send('');
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error instanceof PoppyError)
|
|
125
|
+
return oauthError(ctx, error);
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* `GET web.browser_session_endpoint` (§6, passo 1): a página com o código de uso único e o cookie
|
|
131
|
+
* que o prende a este navegador. Não mexe em Session nem nos outros cookies.
|
|
132
|
+
*/
|
|
133
|
+
async browserSessionPage(ctx) {
|
|
134
|
+
const poppy = await poppyOr404(ctx);
|
|
135
|
+
if (!poppy?.cfg.web?.browserSession)
|
|
136
|
+
return poppy ? ctx.response.notFound() : undefined;
|
|
137
|
+
const { code, cookie, maxAge } = await poppy.startBrowserJoin();
|
|
138
|
+
const name = joinCookieName(poppy);
|
|
139
|
+
ctx.response.append('Set-Cookie', `${name}=${cookie}; Path=/; Max-Age=${maxAge}; ${cookieSecure(poppy)}HttpOnly; SameSite=Strict`);
|
|
140
|
+
browserHeaders(ctx);
|
|
141
|
+
// `code` só tem caracteres base64url; o `action` é o path do próprio endpoint.
|
|
142
|
+
const action = new URL(poppy.urls.browserSession).pathname;
|
|
143
|
+
return ctx.response
|
|
144
|
+
.status(200)
|
|
145
|
+
.send(`<!doctype html><html><head><meta charset="utf-8"><title>Connecting</title></head><body><form method="post" action="${action}"><input type="hidden" name="code" value="${code}"><button>Continue</button></form></body></html>`);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* `POST {browser_session_endpoint}/authorize` (§6, passo 2): o agente autoriza o código, com o
|
|
149
|
+
* header da Session e, se logado, o access token. 204; código inválido → 400 `invalid_request`.
|
|
150
|
+
*/
|
|
151
|
+
async browserSessionAuthorize(ctx) {
|
|
152
|
+
const poppy = await poppyOr404(ctx);
|
|
153
|
+
if (!poppy?.cfg.web?.browserSession)
|
|
154
|
+
return poppy ? ctx.response.notFound() : undefined;
|
|
155
|
+
noStore(ctx);
|
|
156
|
+
try {
|
|
157
|
+
const result = await poppy.authorizeBrowserJoin({
|
|
158
|
+
method: ctx.request.method(),
|
|
159
|
+
url: publicRequestUrl(ctx, poppy),
|
|
160
|
+
headers: ctx.request.headers(),
|
|
161
|
+
}, ctx.request.body()?.code);
|
|
162
|
+
if (!result.ok)
|
|
163
|
+
return writePoppyAuthError(ctx, result);
|
|
164
|
+
return ctx.response.status(204).send('');
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (error instanceof PoppyError) {
|
|
168
|
+
return ctx.response.status(400).json({ error: 'invalid_request' });
|
|
169
|
+
}
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* `POST web.browser_session_endpoint` (§6, passo 3): o navegador submete o código → cookie do app
|
|
175
|
+
* para a Session, limpa o cookie do passo 1 e redireciona para o site; falha → página de erro.
|
|
176
|
+
*/
|
|
177
|
+
async browserSession(ctx) {
|
|
178
|
+
const poppy = await poppyOr404(ctx);
|
|
179
|
+
if (!poppy?.cfg.web?.browserSession)
|
|
180
|
+
return poppy ? ctx.response.notFound() : undefined;
|
|
181
|
+
browserHeaders(ctx);
|
|
182
|
+
const name = joinCookieName(poppy);
|
|
183
|
+
const result = await poppy.completeBrowserJoin(ctx.request.input('code'), readCookie(ctx.request.header('cookie'), name));
|
|
184
|
+
if (!result)
|
|
185
|
+
return badBrowserRequest(ctx);
|
|
186
|
+
await loginPoppyBrowser(ctx, poppy, result);
|
|
187
|
+
ctx.response.append('Set-Cookie', `${name}=; Path=/; Max-Age=0; ${cookieSecure(poppy)}HttpOnly; SameSite=Strict`);
|
|
188
|
+
ctx.response.header('Location', poppy.cfg.web.redirectTo);
|
|
189
|
+
return ctx.response.status(303).send('');
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** `__Host-` exige `Secure`; em dev com o issuer em http o cookie sai sem os dois. */
|
|
193
|
+
function joinCookieName(poppy) {
|
|
194
|
+
return new URL(poppy.urls.origin).protocol === 'https:' ? '__Host-poppy_join' : 'poppy_join';
|
|
195
|
+
}
|
|
196
|
+
function cookieSecure(poppy) {
|
|
197
|
+
return new URL(poppy.urls.origin).protocol === 'https:' ? 'Secure; ' : '';
|
|
198
|
+
}
|
|
199
|
+
function readCookie(header, name) {
|
|
200
|
+
for (const part of (header ?? '').split(';')) {
|
|
201
|
+
const eq = part.indexOf('=');
|
|
202
|
+
if (eq > 0 && part.slice(0, eq).trim() === name)
|
|
203
|
+
return part.slice(eq + 1).trim();
|
|
204
|
+
}
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
/** Sem cache, sem moldura e sem referência da página que abriu (§6, passo 1). */
|
|
208
|
+
function browserHeaders(ctx) {
|
|
209
|
+
noStore(ctx);
|
|
210
|
+
ctx.response.header('Content-Type', 'text/html; charset=utf-8');
|
|
211
|
+
ctx.response.header('Content-Security-Policy', "frame-ancestors 'none'");
|
|
212
|
+
ctx.response.header('Cross-Origin-Opener-Policy', 'same-origin');
|
|
213
|
+
ctx.response.header('Referrer-Policy', 'no-referrer');
|
|
214
|
+
}
|
|
215
|
+
function badBrowserRequest(ctx) {
|
|
216
|
+
return ctx.response
|
|
217
|
+
.status(400)
|
|
218
|
+
.send('<!doctype html><html><head><meta charset="utf-8"><title>Bad request</title></head><body><h1>Invalid browser session request</h1></body></html>');
|
|
219
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { PoppyReplayStore } from './config.js';
|
|
2
|
+
export type DpopFailure = {
|
|
3
|
+
ok: false;
|
|
4
|
+
error: 'invalid_dpop_proof' | 'use_dpop_nonce';
|
|
5
|
+
description: string;
|
|
6
|
+
};
|
|
7
|
+
export type DpopResult = {
|
|
8
|
+
ok: true;
|
|
9
|
+
jkt: string;
|
|
10
|
+
jti: string;
|
|
11
|
+
} | DpopFailure;
|
|
12
|
+
export interface DpopNonceSource {
|
|
13
|
+
/** Nonce novo para o header `DPoP-Nonce`. */
|
|
14
|
+
issue(): string;
|
|
15
|
+
/** O nonce ainda vale? */
|
|
16
|
+
valid(nonce: string): boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Nonces sem estado: `base64url(ts).base64url(hmac(ts))`, válidos por
|
|
20
|
+
* `ttlSeconds` (default 300). Qualquer instância com o mesmo segredo valida.
|
|
21
|
+
*
|
|
22
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.3 — acompanha a spec em desenvolvimento e PODE MUDAR
|
|
23
|
+
* de forma incompatível fora de majors enquanto ela for draft.
|
|
24
|
+
*/
|
|
25
|
+
export declare function hmacNonceSource(secret: Buffer | string, options?: {
|
|
26
|
+
ttlSeconds?: number;
|
|
27
|
+
now?: () => number;
|
|
28
|
+
}): DpopNonceSource;
|
|
29
|
+
/** `ath`: base64url(SHA-256(access token)). */
|
|
30
|
+
export declare function accessTokenHash(token: string): string;
|
|
31
|
+
/**
|
|
32
|
+
* `htu` normalizado para comparação: esquema e host minúsculos, sem porta
|
|
33
|
+
* default, sem query nem fragmento. `null` se não for URL http(s).
|
|
34
|
+
*/
|
|
35
|
+
export declare function normalizeHtu(value: string): string | null;
|
|
36
|
+
export interface VerifyDpopInput {
|
|
37
|
+
/** Valor do(s) header(s) `DPoP`. Mais de um = inválido. */
|
|
38
|
+
proof: string | string[] | undefined | null;
|
|
39
|
+
method: string;
|
|
40
|
+
/** URL da request (a query é ignorada). */
|
|
41
|
+
url: string;
|
|
42
|
+
/** Access token apresentado junto (resource server) — exige `ath`. */
|
|
43
|
+
accessToken?: string;
|
|
44
|
+
/** Thumbprint (RFC 7638) a que o token está preso. */
|
|
45
|
+
expectedJkt?: string;
|
|
46
|
+
algorithms: string[];
|
|
47
|
+
/** Janela do `iat`, em segundos. */
|
|
48
|
+
maxAge: number;
|
|
49
|
+
/** Tolerância de relógio para `iat` no futuro, em segundos. Default: 5. */
|
|
50
|
+
clockSkew?: number;
|
|
51
|
+
replay: PoppyReplayStore;
|
|
52
|
+
nonce?: {
|
|
53
|
+
required: boolean;
|
|
54
|
+
source: DpopNonceSource;
|
|
55
|
+
};
|
|
56
|
+
now?: () => number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.3 — pode mudar de forma incompatível enquanto a spec for draft.
|
|
60
|
+
*/
|
|
61
|
+
export declare function verifyDpopProof(input: VerifyDpopInput): Promise<DpopResult>;
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verificação de provas DPoP (RFC 9449) — utilitário genérico para o token
|
|
3
|
+
* endpoint e para resource servers (§4.5 do Poppy).
|
|
4
|
+
*
|
|
5
|
+
* Confere: um único header `DPoP`; `typ` `dpop+jwt`; algoritmo permitido; `jwk`
|
|
6
|
+
* público no header e a assinatura com ele; `jti`, `htm`, `htu` (sem query nem
|
|
7
|
+
* fragmento), `iat` dentro da janela; `ath` = SHA-256 do access token; o
|
|
8
|
+
* `nonce` quando exigido; replay do `jti` na janela; e, num resource server, que
|
|
9
|
+
* a chave é a do token (`cnf.jkt`).
|
|
10
|
+
*/
|
|
11
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
12
|
+
import { calculateJwkThumbprint, decodeProtectedHeader, EmbeddedJWK, jwtVerify, } from 'jose';
|
|
13
|
+
import { replayKey } from './replay.js';
|
|
14
|
+
/**
|
|
15
|
+
* Nonces sem estado: `base64url(ts).base64url(hmac(ts))`, válidos por
|
|
16
|
+
* `ttlSeconds` (default 300). Qualquer instância com o mesmo segredo valida.
|
|
17
|
+
*
|
|
18
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.3 — acompanha a spec em desenvolvimento e PODE MUDAR
|
|
19
|
+
* de forma incompatível fora de majors enquanto ela for draft.
|
|
20
|
+
*/
|
|
21
|
+
export function hmacNonceSource(secret, options = {}) {
|
|
22
|
+
const ttl = (options.ttlSeconds ?? 300) * 1000;
|
|
23
|
+
const now = options.now ?? Date.now;
|
|
24
|
+
const mac = (ts) => createHmac('sha256', secret).update(`dpop-nonce:${ts}`).digest('base64url');
|
|
25
|
+
return {
|
|
26
|
+
issue() {
|
|
27
|
+
const ts = Buffer.from(String(now())).toString('base64url');
|
|
28
|
+
return `${ts}.${mac(ts)}`;
|
|
29
|
+
},
|
|
30
|
+
valid(nonce) {
|
|
31
|
+
const [ts, sig] = nonce.split('.');
|
|
32
|
+
if (!ts || !sig)
|
|
33
|
+
return false;
|
|
34
|
+
const expected = Buffer.from(mac(ts));
|
|
35
|
+
const given = Buffer.from(sig);
|
|
36
|
+
if (expected.length !== given.length || !timingSafeEqual(expected, given))
|
|
37
|
+
return false;
|
|
38
|
+
const issuedAt = Number(Buffer.from(ts, 'base64url').toString());
|
|
39
|
+
const t = now();
|
|
40
|
+
return Number.isFinite(issuedAt) && issuedAt <= t + 5000 && t - issuedAt <= ttl;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** `ath`: base64url(SHA-256(access token)). */
|
|
45
|
+
export function accessTokenHash(token) {
|
|
46
|
+
return createHash('sha256').update(token).digest('base64url');
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* `htu` normalizado para comparação: esquema e host minúsculos, sem porta
|
|
50
|
+
* default, sem query nem fragmento. `null` se não for URL http(s).
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeHtu(value) {
|
|
53
|
+
try {
|
|
54
|
+
const url = new URL(value);
|
|
55
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:')
|
|
56
|
+
return null;
|
|
57
|
+
url.hash = '';
|
|
58
|
+
url.search = '';
|
|
59
|
+
return url.toString();
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function failure(error, description) {
|
|
66
|
+
return { ok: false, error, description };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* @experimental Poppy (Personal Agent Protocol) Draft 0.3 — pode mudar de forma incompatível enquanto a spec for draft.
|
|
70
|
+
*/
|
|
71
|
+
export async function verifyDpopProof(input) {
|
|
72
|
+
const raw = input.proof;
|
|
73
|
+
if (raw === undefined || raw === null || raw === '') {
|
|
74
|
+
return failure('invalid_dpop_proof', 'DPoP proof is missing');
|
|
75
|
+
}
|
|
76
|
+
if (Array.isArray(raw) ? raw.length !== 1 : raw.includes(',')) {
|
|
77
|
+
return failure('invalid_dpop_proof', 'Exactly one DPoP proof is allowed');
|
|
78
|
+
}
|
|
79
|
+
const proof = Array.isArray(raw) ? raw[0] : raw;
|
|
80
|
+
let header;
|
|
81
|
+
try {
|
|
82
|
+
header = decodeProtectedHeader(proof);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return failure('invalid_dpop_proof', 'Malformed DPoP proof');
|
|
86
|
+
}
|
|
87
|
+
if (header.typ !== 'dpop+jwt')
|
|
88
|
+
return failure('invalid_dpop_proof', 'typ must be dpop+jwt');
|
|
89
|
+
if (!header.alg || !input.algorithms.includes(header.alg)) {
|
|
90
|
+
return failure('invalid_dpop_proof', 'Unsupported DPoP algorithm');
|
|
91
|
+
}
|
|
92
|
+
const jwk = header.jwk;
|
|
93
|
+
if (!jwk || typeof jwk !== 'object')
|
|
94
|
+
return failure('invalid_dpop_proof', 'jwk header is required');
|
|
95
|
+
if ('d' in jwk || jwk.kty === 'oct') {
|
|
96
|
+
return failure('invalid_dpop_proof', 'jwk must be a public key');
|
|
97
|
+
}
|
|
98
|
+
const nowMs = (input.now ?? Date.now)();
|
|
99
|
+
let payload;
|
|
100
|
+
try {
|
|
101
|
+
({ payload } = await jwtVerify(proof, EmbeddedJWK, {
|
|
102
|
+
algorithms: input.algorithms,
|
|
103
|
+
typ: 'dpop+jwt',
|
|
104
|
+
currentDate: new Date(nowMs),
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return failure('invalid_dpop_proof', 'DPoP proof signature is invalid');
|
|
109
|
+
}
|
|
110
|
+
const { jti, htm, htu, iat, ath, nonce } = payload;
|
|
111
|
+
if (typeof jti !== 'string' || jti.length < 8 || jti.length > 256) {
|
|
112
|
+
return failure('invalid_dpop_proof', 'jti is required');
|
|
113
|
+
}
|
|
114
|
+
if (typeof htm !== 'string' || htm !== input.method.toUpperCase()) {
|
|
115
|
+
return failure('invalid_dpop_proof', 'htm does not match the request method');
|
|
116
|
+
}
|
|
117
|
+
const expectedHtu = normalizeHtu(input.url);
|
|
118
|
+
if (typeof htu !== 'string' || !expectedHtu || normalizeHtu(htu) !== expectedHtu) {
|
|
119
|
+
return failure('invalid_dpop_proof', 'htu does not match the request URL');
|
|
120
|
+
}
|
|
121
|
+
const nowS = Math.floor(nowMs / 1000);
|
|
122
|
+
const skew = input.clockSkew ?? 5;
|
|
123
|
+
if (typeof iat !== 'number' || iat > nowS + skew || iat < nowS - input.maxAge) {
|
|
124
|
+
return failure('invalid_dpop_proof', 'iat is outside the acceptance window');
|
|
125
|
+
}
|
|
126
|
+
if (input.accessToken !== undefined) {
|
|
127
|
+
if (typeof ath !== 'string' || ath !== accessTokenHash(input.accessToken)) {
|
|
128
|
+
return failure('invalid_dpop_proof', 'ath does not match the access token');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
let jkt;
|
|
132
|
+
try {
|
|
133
|
+
jkt = await calculateJwkThumbprint(jwk, 'sha256');
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return failure('invalid_dpop_proof', 'Invalid jwk');
|
|
137
|
+
}
|
|
138
|
+
if (input.expectedJkt !== undefined && jkt !== input.expectedJkt) {
|
|
139
|
+
return failure('invalid_dpop_proof', 'DPoP key does not match the token binding');
|
|
140
|
+
}
|
|
141
|
+
if (input.nonce?.required) {
|
|
142
|
+
if (typeof nonce !== 'string' || !input.nonce.source.valid(nonce)) {
|
|
143
|
+
return failure('use_dpop_nonce', 'A DPoP nonce issued by the server is required');
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
else if (nonce !== undefined && input.nonce && typeof nonce === 'string') {
|
|
147
|
+
// Nonce mandado sem ser exigido: se vier, tem de ser um nosso e válido.
|
|
148
|
+
if (!input.nonce.source.valid(nonce)) {
|
|
149
|
+
return failure('use_dpop_nonce', 'The DPoP nonce is invalid or expired');
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Replay por último: uma prova inválida não queima o `jti`.
|
|
153
|
+
const expiresAt = new Date((iat + input.maxAge + skew) * 1000);
|
|
154
|
+
if (!(await input.replay.claim(replayKey('dpop', jkt, jti), expiresAt))) {
|
|
155
|
+
return failure('invalid_dpop_proof', 'DPoP proof was already used');
|
|
156
|
+
}
|
|
157
|
+
return { ok: true, jkt, jti };
|
|
158
|
+
}
|