@yaks/oauth 0.0.0-stage → 0.2.36

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/client.js ADDED
@@ -0,0 +1,219 @@
1
+ // The authorization-code client for a provider described as data (RFC 6749
2
+ // §4.1, with PKCE from RFC 7636): the link a person follows, the exchange of
3
+ // the code that comes back, and the refresh that keeps the grant alive.
4
+ //
5
+ // It keeps nothing of its own. The attempt in flight goes back to the caller,
6
+ // who holds it across the redirect however its host can (a sealed cookie, a
7
+ // short-lived record), because the request that begins and the request that
8
+ // completes may not share a process. The tokens go to the AuthorizationStore
9
+ // it is given — @yaks/secrets `records()` keeps them in a vault — and a
10
+ // refresh happens inside that store's update, so two callers refreshing one
11
+ // grant at once never both spend the refresh token. Web APIs only, so the same
12
+ // client runs under Deno and in a Worker.
13
+ import { attempt, pkce } from "./mod.js";
14
+ /** The provider's refusal, carrying its error code: `invalid_grant` is a grant
15
+ * revoked or a refresh token already spent, and means connect again. */ export class OAuthError extends Error {
16
+ code;
17
+ constructor(code, message){
18
+ super(message);
19
+ this.name = 'OAuthError';
20
+ this.code = code;
21
+ }
22
+ }
23
+ // A token this close to expiry is refreshed before use, so a call made with
24
+ // it does not fail on the wire.
25
+ let SKEW = 60_000;
26
+ // Form encoding, which is also how RFC 6749 §2.3.1 wants a client's id and
27
+ // secret encoded before they are joined for Basic.
28
+ let form = (fields)=>new URLSearchParams(Object.entries(fields).filter((f)=>f[1] != null));
29
+ let enc = (s)=>form({
30
+ s
31
+ }).toString().slice(2);
32
+ // The return address with the attempt's state on it, for a flow whose
33
+ // provider carries none back itself.
34
+ let stated = (redirect, state)=>{
35
+ let to = new URL(redirect);
36
+ to.searchParams.set('state', state);
37
+ return to.href;
38
+ };
39
+ let str = (v)=>typeof v == 'string' && v ? v : undefined;
40
+ // Every field, so a new grant replaces the old one whole rather than keeping
41
+ // a stale refresh token or scope beside it.
42
+ let NONE = {
43
+ access_token: undefined,
44
+ token_type: undefined,
45
+ id_token: undefined,
46
+ refresh_token: undefined,
47
+ expires_at: undefined,
48
+ scope: undefined
49
+ };
50
+ // A dotted path's value in an answer, as a string, where it is one.
51
+ let named = (body, path)=>{
52
+ let v = body;
53
+ for (let k of path?.split('.') ?? []){
54
+ v = v && typeof v == 'object' ? v[k] : undefined;
55
+ }
56
+ return path && (typeof v == 'string' || typeof v == 'number') ? String(v) : undefined;
57
+ };
58
+ export let client = (provider, o)=>{
59
+ let now = o.now ?? Date.now;
60
+ let key = provider.answers == 'key';
61
+ let fresh = (t)=>!!t.access_token && (t.expires_at == null || t.expires_at - SKEW > now());
62
+ let exchange = async (fields, was = {}, encoding = 'form')=>{
63
+ let id = provider.client?.id;
64
+ let secret = provider.client?.secret;
65
+ let pair = id != null && secret != null && (provider.auth ?? 'basic') == 'basic' ? `${enc(id)}:${enc(secret)}` : undefined;
66
+ let basic = pair != null;
67
+ // A redirect is answered, never followed, so the code and the secret
68
+ // reach the token endpoint alone: `manual` hands back the 3xx, which is
69
+ // not ok and so refused below. (Workers has no `error` mode.)
70
+ let res = await (o.fetch ?? fetch)(provider.token, {
71
+ method: 'POST',
72
+ redirect: 'manual',
73
+ signal: AbortSignal.timeout(30_000),
74
+ headers: {
75
+ 'content-type': key || encoding == 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
76
+ accept: 'application/json',
77
+ ...pair ? {
78
+ authorization: `Basic ${btoa(pair)}`
79
+ } : {}
80
+ },
81
+ body: key ? JSON.stringify(fields) : encoding == 'json' ? JSON.stringify({
82
+ ...fields,
83
+ resource: provider.resource,
84
+ client_id: basic ? undefined : id,
85
+ client_secret: basic ? undefined : secret
86
+ }) : form({
87
+ ...fields,
88
+ resource: provider.resource,
89
+ client_id: basic ? undefined : id,
90
+ client_secret: basic ? undefined : secret
91
+ })
92
+ });
93
+ let said = await res.json().catch(()=>({}));
94
+ let body = said && typeof said == 'object' ? said : {};
95
+ let access = str(key ? body.key : body.access_token);
96
+ // Some providers answer a refusal with 200 and an `error` field.
97
+ if (!res.ok || !access) {
98
+ let code = str(body?.error) ?? `http_${res.status}`;
99
+ throw new OAuthError(code, `the token endpoint refused: ${code}`);
100
+ }
101
+ let life = Number(body.expires_in);
102
+ return {
103
+ access_token: access,
104
+ token_type: str(body.token_type),
105
+ id_token: str(body.id_token) ?? was.id_token,
106
+ // A refresh may or may not issue a new refresh token (RFC 6749 §6).
107
+ refresh_token: str(body.refresh_token) ?? was.refresh_token,
108
+ expires_at: Number.isFinite(life) && life > 0 ? now() + life * 1000 : undefined,
109
+ scope: str(body.scope)?.split(provider.scopeSeparator ?? /\s+/).map((scope)=>scope.trim()).filter(Boolean).join(' ') ?? was.scope,
110
+ account: named(body, provider.account) ?? was.account,
111
+ account_title: named(body, provider.account_title) ?? was.account_title
112
+ };
113
+ };
114
+ let renew = (stale)=>o.store.update(o.key, async (record)=>{
115
+ // Another caller may have refreshed while this one waited its turn.
116
+ if (record.access_token != stale && fresh(record)) {
117
+ return record.access_token;
118
+ }
119
+ if (!record.refresh_token) {
120
+ if (!record.access_token) return undefined;
121
+ throw new OAuthError('expired', 'the grant expired; connect again');
122
+ }
123
+ let got = await exchange({
124
+ grant_type: 'refresh_token',
125
+ refresh_token: record.refresh_token
126
+ }, record, provider.refreshEncoding);
127
+ Object.assign(record, NONE, got);
128
+ return record.access_token;
129
+ });
130
+ let exchangeCode = (code, verifier, redirect)=>exchange(key ? {
131
+ code,
132
+ code_verifier: verifier,
133
+ code_challenge_method: 'S256'
134
+ } : {
135
+ grant_type: 'authorization_code',
136
+ code,
137
+ ...redirect ? {
138
+ redirect_uri: redirect
139
+ } : {},
140
+ ...verifier && provider.pkce !== false ? {
141
+ code_verifier: verifier
142
+ } : {}
143
+ });
144
+ return {
145
+ redeem: async (code)=>{
146
+ if (key || provider.pkce !== false || !provider.client?.secret) {
147
+ throw new OAuthError('callback', 'this client needs a local authorization attempt');
148
+ }
149
+ return await exchangeCode(code);
150
+ },
151
+ begin: async (scopes = provider.scopes ?? [])=>{
152
+ let { verifier, challenge } = await pkce();
153
+ let pending = {
154
+ ...attempt(now()),
155
+ verifier
156
+ };
157
+ let url = new URL(provider.authorize);
158
+ let fields = {
159
+ ...provider.params,
160
+ ...key ? {
161
+ callback_url: stated(o.redirect, pending.state)
162
+ } : {
163
+ response_type: 'code',
164
+ client_id: provider.client?.id,
165
+ redirect_uri: o.redirect,
166
+ state: pending.state,
167
+ resource: provider.resource,
168
+ ...scopes.length ? {
169
+ scope: scopes.join(provider.scopeSeparator ?? ' ')
170
+ } : {}
171
+ },
172
+ ...provider.pkce === false ? {} : {
173
+ code_challenge: challenge,
174
+ code_challenge_method: 'S256'
175
+ }
176
+ };
177
+ for (let [k, v] of form(fields))url.searchParams.set(k, v);
178
+ return {
179
+ url: url.href,
180
+ attempt: pending
181
+ };
182
+ },
183
+ complete: async (pending, callback)=>{
184
+ let q;
185
+ try {
186
+ q = new URL(callback).searchParams;
187
+ } catch {
188
+ throw new OAuthError('callback', 'the return URL is invalid');
189
+ }
190
+ if (!pending.verifier || pending.until <= now()) {
191
+ throw new OAuthError('expired', 'the authorization expired; begin again');
192
+ }
193
+ if (q.get('state') != pending.state) {
194
+ throw new OAuthError('state', 'the return does not match this attempt');
195
+ }
196
+ if (provider.issuer && q.get('iss') != provider.issuer) {
197
+ throw new OAuthError('issuer', 'the return names another issuer');
198
+ }
199
+ let error = q.get('error');
200
+ if (error) throw new OAuthError(error, `authorization refused: ${error}`);
201
+ let codes = q.getAll('code');
202
+ if (codes.length != 1 || !codes[0]) {
203
+ throw new OAuthError('code', 'the return carried no single code');
204
+ }
205
+ let got = await exchangeCode(codes[0], pending.verifier, o.redirect);
206
+ await o.store.update(o.key, (record)=>{
207
+ Object.assign(record, NONE, got);
208
+ return Promise.resolve();
209
+ });
210
+ },
211
+ token: async ()=>{
212
+ let t = await o.store.read(o.key);
213
+ if (!t?.access_token) return undefined;
214
+ return fresh(t) ? t.access_token : renew(t.access_token);
215
+ },
216
+ refresh: (stale)=>renew(stale)
217
+ };
218
+ };
219
+ //# sourceMappingURL=client.js.map
package/client.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sources":["./client.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,6EAA6E;AAC7E,wEAAwE;AACxE,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAC7E,wEAAwE;AACxE,4EAA4E;AAC5E,+EAA+E;AAC/E,0CAA0C;AAE1C,SAAuB,OAAO,EAA2B,IAAI,mBAAkB;AA6D/E;sEACsE,GACtE,OAAO,MAAM,mBAAmB;EAC9B,KAAY;EACZ,YAAY,IAAY,EAAE,OAAe,CAAE;IACzC,KAAK,CAAC;IACN,IAAI,CAAC,IAAI,GAAG;IACZ,IAAI,CAAC,IAAI,GAAG;EACd;AACF;AA8BA,4EAA4E;AAC5E,gCAAgC;AAChC,IAAI,OAAO;AAEX,2EAA2E;AAC3E,mDAAmD;AACnD,IAAI,OAAO,CAAC,SACV,IAAI,gBACF,OAAO,OAAO,CAAC,QAAQ,MAAM,CAAC,CAAC,IAA6B,CAAC,CAAC,EAAE,IAAI;AAExE,IAAI,MAAM,CAAC,IAAc,KAAK;IAAE;EAAE,GAAG,QAAQ,GAAG,KAAK,CAAC;AAEtD,sEAAsE;AACtE,qCAAqC;AACrC,IAAI,SAAS,CAAC,UAAkB;EAC9B,IAAI,KAAK,IAAI,IAAI;EACjB,GAAG,YAAY,CAAC,GAAG,CAAC,SAAS;EAC7B,OAAO,GAAG,IAAI;AAChB;AAEA,IAAI,MAAM,CAAC,IAAe,OAAO,KAAK,YAAY,IAAI,IAAI;AAE1D,6EAA6E;AAC7E,4CAA4C;AAC5C,IAAI,OAAe;EACjB,cAAc;EACd,YAAY;EACZ,UAAU;EACV,eAAe;EACf,YAAY;EACZ,OAAO;AACT;AAEA,oEAAoE;AACpE,IAAI,QAAQ,CAAC,MAA+B;EAC1C,IAAI,IAAa;EACjB,KAAK,IAAI,KAAK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,CAAC,EAAE,GAAG;MAChC,IAAI,CAAC,GAAG,cAAc,OAAO;MAC7B,OAAO,MAAM,KAAK,EAAE,YAAY,GAAG,MAAM,EAAE,YAAY;IACzD;IAEA,SAAS,CAAC,QAAU,MAAM;EAC5B;AACF,EAAC"}
package/client.ts ADDED
@@ -0,0 +1,342 @@
1
+ // The authorization-code client for a provider described as data (RFC 6749
2
+ // §4.1, with PKCE from RFC 7636): the link a person follows, the exchange of
3
+ // the code that comes back, and the refresh that keeps the grant alive.
4
+ //
5
+ // It keeps nothing of its own. The attempt in flight goes back to the caller,
6
+ // who holds it across the redirect however its host can (a sealed cookie, a
7
+ // short-lived record), because the request that begins and the request that
8
+ // completes may not share a process. The tokens go to the AuthorizationStore
9
+ // it is given — @yaks/secrets `records()` keeps them in a vault — and a
10
+ // refresh happens inside that store's update, so two callers refreshing one
11
+ // grant at once never both spend the refresh token. Web APIs only, so the same
12
+ // client runs under Deno and in a Worker.
13
+
14
+ import { type Attempt, attempt, type AuthorizationStore, pkce } from './mod.js'
15
+
16
+ /** An OAuth provider as data: where a person authorizes, where codes and
17
+ * refresh tokens are exchanged, and the client registered with it. */
18
+ export type Provider = {
19
+ authorize: string
20
+ token: string
21
+ scopes?: string[]
22
+ /** Delimiter used by this provider for requested and granted scopes. */
23
+ scopeSeparator?: ' ' | ','
24
+ /** A confidential client whose provider requires PKCE to be omitted. */
25
+ pkce?: boolean
26
+ /** Extra authorize parameters the provider wants, such as Google's
27
+ * `access_type: 'offline'` for a refresh token. They never replace the
28
+ * flow's own (state, challenge, redirect). */
29
+ params?: Record<string, string>
30
+ /** The client registered with it; one that answers a key has none. */
31
+ client?: { id: string; secret?: string }
32
+ /** How a confidential client authenticates at the token endpoint: HTTP
33
+ * Basic, which every server must accept (RFC 6749 §2.3.1), or in the form
34
+ * body. A client with no secret sends its id in the body either way. */
35
+ auth?: 'basic' | 'post'
36
+ /** A provider may require JSON for refresh while codes exchange as form. */
37
+ refreshEncoding?: 'form' | 'json'
38
+ /** What the exchange answers: tokens, or an API key, as OpenRouter's PKCE
39
+ * does. A key is kept as an access token that never expires. Its flow has
40
+ * no `state` parameter, so the attempt's state rides the `callback_url`,
41
+ * and the return names its attempt as every other flow's does. */
42
+ answers?: 'tokens' | 'key'
43
+ /** The resource the grant is for (RFC 8707), as an MCP server asks: sent
44
+ * with the link and with every exchange. */
45
+ resource?: string
46
+ /** The issuer every return must name (RFC 9207), for a server that says it
47
+ * names one: a return from any other server is refused. */
48
+ issuer?: string
49
+ /** The field of the token endpoint's answer that names the account the
50
+ * grant is for, as a dotted path, where the answer says it: Discord's
51
+ * `guild.id`, the server a bot was added to. It is kept as `account`. */
52
+ account?: string
53
+ /** The field of the token endpoint's answer that names that account for
54
+ * people, as a dotted path: Discord's `guild.name`. It is kept as
55
+ * `account_title`. */
56
+ account_title?: string
57
+ }
58
+
59
+ /** One grant, as the store keeps it. `expires_at` is epoch milliseconds. */
60
+ export type Tokens = {
61
+ access_token?: string
62
+ token_type?: string
63
+ /** OpenID identity returned by the provider, retained across refresh. */
64
+ id_token?: string
65
+ refresh_token?: string
66
+ expires_at?: number
67
+ scope?: string
68
+ /** What the provider's `account` field said, retained across refresh. */
69
+ account?: string
70
+ /** What the provider's `account_title` field said, retained across
71
+ * refresh. */
72
+ account_title?: string
73
+ }
74
+
75
+ /** The provider's refusal, carrying its error code: `invalid_grant` is a grant
76
+ * revoked or a refresh token already spent, and means connect again. */
77
+ export class OAuthError extends Error {
78
+ code: string
79
+ constructor(code: string, message: string) {
80
+ super(message)
81
+ this.name = 'OAuthError'
82
+ this.code = code
83
+ }
84
+ }
85
+
86
+ export type Options = {
87
+ store: AuthorizationStore<Tokens>
88
+ /** The store key the grant lives under, such as a connection's eid. */
89
+ key: string
90
+ /** Where the provider sends the person back, as registered with it. */
91
+ redirect: string
92
+ fetch?: typeof fetch
93
+ now?: () => number
94
+ }
95
+
96
+ export type Client = {
97
+ /** The link to send a person to, and the attempt to hold until they
98
+ * return. */
99
+ begin: (
100
+ scopes?: string[],
101
+ ) => Promise<{ url: string; attempt: Attempt & { verifier: string } }>
102
+ /** Exchange the code the return URL carries and keep the grant. */
103
+ complete: (pending: Attempt, callback: string | URL) => Promise<void>
104
+ /** Redeem a provider-started installation for later, explicit attachment. */
105
+ redeem: (code: string) => Promise<Tokens>
106
+ /** A usable access token, refreshed first when it is about to expire;
107
+ * undefined when there is no grant. */
108
+ token: () => Promise<string | undefined>
109
+ /** A new access token after the provider refused `stale`, unless another
110
+ * caller has already replaced it. */
111
+ refresh: (stale: string) => Promise<string | undefined>
112
+ }
113
+
114
+ // A token this close to expiry is refreshed before use, so a call made with
115
+ // it does not fail on the wire.
116
+ let SKEW = 60_000
117
+
118
+ // Form encoding, which is also how RFC 6749 §2.3.1 wants a client's id and
119
+ // secret encoded before they are joined for Basic.
120
+ let form = (fields: Record<string, string | undefined>) =>
121
+ new URLSearchParams(
122
+ Object.entries(fields).filter((f): f is [string, string] => f[1] != null),
123
+ )
124
+ let enc = (s: string) => form({ s }).toString().slice(2)
125
+
126
+ // The return address with the attempt's state on it, for a flow whose
127
+ // provider carries none back itself.
128
+ let stated = (redirect: string, state: string) => {
129
+ let to = new URL(redirect)
130
+ to.searchParams.set('state', state)
131
+ return to.href
132
+ }
133
+
134
+ let str = (v: unknown) => typeof v == 'string' && v ? v : undefined
135
+
136
+ // Every field, so a new grant replaces the old one whole rather than keeping
137
+ // a stale refresh token or scope beside it.
138
+ let NONE: Tokens = {
139
+ access_token: undefined,
140
+ token_type: undefined,
141
+ id_token: undefined,
142
+ refresh_token: undefined,
143
+ expires_at: undefined,
144
+ scope: undefined,
145
+ }
146
+
147
+ // A dotted path's value in an answer, as a string, where it is one.
148
+ let named = (body: Record<string, unknown>, path?: string) => {
149
+ let v: unknown = body
150
+ for (let k of path?.split('.') ?? []) {
151
+ v = v && typeof v == 'object'
152
+ ? (v as Record<string, unknown>)[k]
153
+ : undefined
154
+ }
155
+ return path && (typeof v == 'string' || typeof v == 'number')
156
+ ? String(v)
157
+ : undefined
158
+ }
159
+
160
+ export let client = (provider: Provider, o: Options): Client => {
161
+ let now = o.now ?? Date.now
162
+ let key = provider.answers == 'key'
163
+ let fresh = (t: Tokens) =>
164
+ !!t.access_token && (t.expires_at == null || t.expires_at - SKEW > now())
165
+
166
+ let exchange = async (
167
+ fields: Record<string, string>,
168
+ was: Tokens = {},
169
+ encoding: 'form' | 'json' = 'form',
170
+ ): Promise<Tokens> => {
171
+ let id = provider.client?.id
172
+ let secret = provider.client?.secret
173
+ let pair = id != null && secret != null &&
174
+ (provider.auth ?? 'basic') == 'basic'
175
+ ? `${enc(id)}:${enc(secret)}`
176
+ : undefined
177
+ let basic = pair != null
178
+ // A redirect is answered, never followed, so the code and the secret
179
+ // reach the token endpoint alone: `manual` hands back the 3xx, which is
180
+ // not ok and so refused below. (Workers has no `error` mode.)
181
+ let res = await (o.fetch ?? fetch)(provider.token, {
182
+ method: 'POST',
183
+ redirect: 'manual',
184
+ signal: AbortSignal.timeout(30_000),
185
+ headers: {
186
+ 'content-type': key || encoding == 'json'
187
+ ? 'application/json'
188
+ : 'application/x-www-form-urlencoded',
189
+ accept: 'application/json',
190
+ ...(pair ? { authorization: `Basic ${btoa(pair)}` } : {}),
191
+ },
192
+ body: key ? JSON.stringify(fields) : encoding == 'json'
193
+ ? JSON.stringify({
194
+ ...fields,
195
+ resource: provider.resource,
196
+ client_id: basic ? undefined : id,
197
+ client_secret: basic ? undefined : secret,
198
+ })
199
+ : form({
200
+ ...fields,
201
+ resource: provider.resource,
202
+ client_id: basic ? undefined : id,
203
+ client_secret: basic ? undefined : secret,
204
+ }),
205
+ })
206
+ let said: unknown = await res.json().catch(() => ({}))
207
+ let body = (said && typeof said == 'object' ? said : {}) as Record<
208
+ string,
209
+ unknown
210
+ >
211
+ let access = str(key ? body.key : body.access_token)
212
+ // Some providers answer a refusal with 200 and an `error` field.
213
+ if (!res.ok || !access) {
214
+ let code = str(body?.error) ?? `http_${res.status}`
215
+ throw new OAuthError(code, `the token endpoint refused: ${code}`)
216
+ }
217
+ let life = Number(body.expires_in)
218
+ return {
219
+ access_token: access,
220
+ token_type: str(body.token_type),
221
+ id_token: str(body.id_token) ?? was.id_token,
222
+ // A refresh may or may not issue a new refresh token (RFC 6749 §6).
223
+ refresh_token: str(body.refresh_token) ?? was.refresh_token,
224
+ expires_at: Number.isFinite(life) && life > 0
225
+ ? now() + life * 1000
226
+ : undefined,
227
+ scope: str(body.scope)?.split(provider.scopeSeparator ?? /\s+/)
228
+ .map((scope) => scope.trim()).filter(Boolean).join(' ') ?? was.scope,
229
+ account: named(body, provider.account) ?? was.account,
230
+ account_title: named(body, provider.account_title) ?? was.account_title,
231
+ }
232
+ }
233
+
234
+ let renew = (stale?: string) =>
235
+ o.store.update(o.key, async (record) => {
236
+ // Another caller may have refreshed while this one waited its turn.
237
+ if (record.access_token != stale && fresh(record)) {
238
+ return record.access_token
239
+ }
240
+ if (!record.refresh_token) {
241
+ if (!record.access_token) return undefined
242
+ throw new OAuthError('expired', 'the grant expired; connect again')
243
+ }
244
+ let got = await exchange(
245
+ { grant_type: 'refresh_token', refresh_token: record.refresh_token },
246
+ record,
247
+ provider.refreshEncoding,
248
+ )
249
+ Object.assign(record, NONE, got)
250
+ return record.access_token
251
+ })
252
+
253
+ let exchangeCode = (code: string, verifier?: string, redirect?: string) =>
254
+ exchange(
255
+ key
256
+ ? { code, code_verifier: verifier!, code_challenge_method: 'S256' }
257
+ : {
258
+ grant_type: 'authorization_code',
259
+ code,
260
+ ...redirect ? { redirect_uri: redirect } : {},
261
+ ...verifier && provider.pkce !== false
262
+ ? { code_verifier: verifier }
263
+ : {},
264
+ },
265
+ )
266
+
267
+ return {
268
+ redeem: async (code) => {
269
+ if (key || provider.pkce !== false || !provider.client?.secret) {
270
+ throw new OAuthError(
271
+ 'callback',
272
+ 'this client needs a local authorization attempt',
273
+ )
274
+ }
275
+ return await exchangeCode(code)
276
+ },
277
+ begin: async (scopes = provider.scopes ?? []) => {
278
+ let { verifier, challenge } = await pkce()
279
+ let pending = { ...attempt(now()), verifier }
280
+ let url = new URL(provider.authorize)
281
+ let fields = {
282
+ ...provider.params,
283
+ ...key ? { callback_url: stated(o.redirect, pending.state) } : {
284
+ response_type: 'code',
285
+ client_id: provider.client?.id,
286
+ redirect_uri: o.redirect,
287
+ state: pending.state,
288
+ resource: provider.resource,
289
+ ...(scopes.length
290
+ ? { scope: scopes.join(provider.scopeSeparator ?? ' ') }
291
+ : {}),
292
+ },
293
+ ...provider.pkce === false ? {} : {
294
+ code_challenge: challenge,
295
+ code_challenge_method: 'S256',
296
+ },
297
+ }
298
+ for (let [k, v] of form(fields)) url.searchParams.set(k, v)
299
+ return { url: url.href, attempt: pending }
300
+ },
301
+
302
+ complete: async (pending, callback) => {
303
+ let q: URLSearchParams
304
+ try {
305
+ q = new URL(callback).searchParams
306
+ } catch {
307
+ throw new OAuthError('callback', 'the return URL is invalid')
308
+ }
309
+ if (!pending.verifier || pending.until <= now()) {
310
+ throw new OAuthError(
311
+ 'expired',
312
+ 'the authorization expired; begin again',
313
+ )
314
+ }
315
+ if (q.get('state') != pending.state) {
316
+ throw new OAuthError('state', 'the return does not match this attempt')
317
+ }
318
+ if (provider.issuer && q.get('iss') != provider.issuer) {
319
+ throw new OAuthError('issuer', 'the return names another issuer')
320
+ }
321
+ let error = q.get('error')
322
+ if (error) throw new OAuthError(error, `authorization refused: ${error}`)
323
+ let codes = q.getAll('code')
324
+ if (codes.length != 1 || !codes[0]) {
325
+ throw new OAuthError('code', 'the return carried no single code')
326
+ }
327
+ let got = await exchangeCode(codes[0], pending.verifier, o.redirect)
328
+ await o.store.update(o.key, (record) => {
329
+ Object.assign(record, NONE, got)
330
+ return Promise.resolve()
331
+ })
332
+ },
333
+
334
+ token: async () => {
335
+ let t = await o.store.read(o.key)
336
+ if (!t?.access_token) return undefined
337
+ return fresh(t) ? t.access_token : renew(t.access_token)
338
+ },
339
+
340
+ refresh: (stale) => renew(stale),
341
+ }
342
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/oauth","version":"0.2.36","license":"Apache-2.0","description":"The OAuth authorization-code client for a provider described as data, and its building blocks: a serialized store of private authorization records, PKCE verifiers and challenges, and correlated attempts with deadlines.","exports":{".":"./mod.ts"},"imports":{"@yaks/oauth":"./mod.ts"}}
package/identity.js ADDED
@@ -0,0 +1,69 @@
1
+ // Who an OpenID Connect provider says signed in: the claims of the id_token
2
+ // its token endpoint answered (OpenID Connect Core 1.0 §2, §3.1.3.7).
3
+ //
4
+ // The token came straight from the token endpoint over TLS, in exchange for a
5
+ // code this client's PKCE verifier and secret were spent on, so TLS stands in
6
+ // for checking its signature (§3.1.3.7, item 6). What is still checked here is
7
+ // that it is from the issuer asked, for this client, and not expired.
8
+ import { OAuthError } from "./client.js";
9
+ /** The claims a JWT carries, unchecked; an empty object for one that is not
10
+ * three parts with a JSON object in the middle. */ export let claims = (jwt)=>{
11
+ try {
12
+ let part = jwt.split('.')[1] ?? '';
13
+ let bytes = Uint8Array.from(atob(part.replaceAll('-', '+').replaceAll('_', '/')), (c)=>c.charCodeAt(0));
14
+ let body = JSON.parse(new TextDecoder().decode(bytes));
15
+ return body && typeof body == 'object' && !Array.isArray(body) ? body : {};
16
+ } catch {
17
+ return {};
18
+ }
19
+ };
20
+ let refused = (why)=>new OAuthError('id_token', `the id_token ${why}`);
21
+ /**
22
+ * Who `tokens`' id_token says signed in, refused unless it is from an issuer
23
+ * `expect` names, for its audience, and still standing.
24
+ *
25
+ * ```ts
26
+ * import { identity } from './identity.ts'
27
+ * import { assertEquals, assertThrows } from '@std/assert'
28
+ * let jwt = (c: object) => `h.${btoa(JSON.stringify(c))}.s`
29
+ * let said = {
30
+ * iss: 'https://id.test', aud: 'me', sub: '7', exp: 2e9,
31
+ * email: 'Ada@Example.com', email_verified: true, name: 'Ada',
32
+ * }
33
+ * let expect = { issuers: ['https://id.test'], audience: 'me', now: 0 }
34
+ * assertEquals(identity({ id_token: jwt(said) }, expect), {
35
+ * issuer: 'https://id.test', subject: '7', email: 'ada@example.com',
36
+ * verified: true, name: 'Ada',
37
+ * })
38
+ * assertThrows(() => identity({ id_token: jwt({ ...said, aud: 'you' }) }, expect))
39
+ * assertThrows(() => identity({}, expect))
40
+ * ```
41
+ */ export let identity = (tokens, expect)=>{
42
+ if (!tokens.id_token) throw refused('is missing');
43
+ let c = claims(tokens.id_token);
44
+ let iss = typeof c.iss == 'string' ? c.iss : '';
45
+ if (!expect.issuers.includes(iss)) throw refused('names another issuer');
46
+ let aud = Array.isArray(c.aud) ? c.aud : [
47
+ c.aud
48
+ ];
49
+ if (!aud.includes(expect.audience)) throw refused('is for another client');
50
+ if (aud.length > 1 && c.azp != expect.audience) {
51
+ throw refused('was authorized for another client');
52
+ }
53
+ let exp = Number(c.exp);
54
+ if (!(exp * 1000 > (expect.now ?? Date.now()))) throw refused('expired');
55
+ if (typeof c.sub != 'string' || !c.sub) throw refused('names nobody');
56
+ let email = typeof c.email == 'string' && c.email.includes('@') ? c.email.trim().toLowerCase() : undefined;
57
+ return {
58
+ issuer: iss,
59
+ subject: c.sub,
60
+ ...email ? {
61
+ email
62
+ } : {},
63
+ verified: c.email_verified === true || c.email_verified === 'true',
64
+ ...typeof c.name == 'string' && c.name ? {
65
+ name: c.name
66
+ } : {}
67
+ };
68
+ };
69
+ //# sourceMappingURL=identity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.js","sources":["./identity.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,8EAA8E;AAC9E,+EAA+E;AAC/E,sEAAsE;AAEtE,SAAS,UAAU,sBAAkC;AAoBrD;iDACiD,GACjD,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI;IACF,IAAI,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI;IAChC,IAAI,QAAQ,WAAW,IAAI,CACzB,KAAK,KAAK,UAAU,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