@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/identity.ts ADDED
@@ -0,0 +1,91 @@
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
+
9
+ import { OAuthError, type Tokens } from './client.js'
10
+
11
+ /** What a provider vouches for: who, and the address it says is theirs. */
12
+ export type Identity = {
13
+ issuer: string
14
+ subject: string
15
+ email?: string
16
+ /** Whether the provider says it checked the address belongs to them. */
17
+ verified: boolean
18
+ name?: string
19
+ }
20
+
21
+ /** What an id_token must say to be believed: an issuer among `issuers`, an
22
+ * audience naming `audience` (the client id), and an expiry after `now`. */
23
+ export type Expect = {
24
+ issuers: string[]
25
+ audience: string
26
+ now?: number
27
+ }
28
+
29
+ /** The claims a JWT carries, unchecked; an empty object for one that is not
30
+ * three parts with a JSON object in the middle. */
31
+ export let claims = (jwt: string): Record<string, unknown> => {
32
+ try {
33
+ let part = jwt.split('.')[1] ?? ''
34
+ let bytes = Uint8Array.from(
35
+ atob(part.replaceAll('-', '+').replaceAll('_', '/')),
36
+ (c) => c.charCodeAt(0),
37
+ )
38
+ let body = JSON.parse(new TextDecoder().decode(bytes))
39
+ return body && typeof body == 'object' && !Array.isArray(body) ? body : {}
40
+ } catch {
41
+ return {}
42
+ }
43
+ }
44
+
45
+ let refused = (why: string) => new OAuthError('id_token', `the id_token ${why}`)
46
+
47
+ /**
48
+ * Who `tokens`' id_token says signed in, refused unless it is from an issuer
49
+ * `expect` names, for its audience, and still standing.
50
+ *
51
+ * ```ts
52
+ * import { identity } from './identity.ts'
53
+ * import { assertEquals, assertThrows } from '@std/assert'
54
+ * let jwt = (c: object) => `h.${btoa(JSON.stringify(c))}.s`
55
+ * let said = {
56
+ * iss: 'https://id.test', aud: 'me', sub: '7', exp: 2e9,
57
+ * email: 'Ada@Example.com', email_verified: true, name: 'Ada',
58
+ * }
59
+ * let expect = { issuers: ['https://id.test'], audience: 'me', now: 0 }
60
+ * assertEquals(identity({ id_token: jwt(said) }, expect), {
61
+ * issuer: 'https://id.test', subject: '7', email: 'ada@example.com',
62
+ * verified: true, name: 'Ada',
63
+ * })
64
+ * assertThrows(() => identity({ id_token: jwt({ ...said, aud: 'you' }) }, expect))
65
+ * assertThrows(() => identity({}, expect))
66
+ * ```
67
+ */
68
+ export let identity = (tokens: Tokens, expect: Expect): Identity => {
69
+ if (!tokens.id_token) throw refused('is missing')
70
+ let c = claims(tokens.id_token)
71
+ let iss = typeof c.iss == 'string' ? c.iss : ''
72
+ if (!expect.issuers.includes(iss)) throw refused('names another issuer')
73
+ let aud = Array.isArray(c.aud) ? c.aud : [c.aud]
74
+ if (!aud.includes(expect.audience)) throw refused('is for another client')
75
+ if (aud.length > 1 && c.azp != expect.audience) {
76
+ throw refused('was authorized for another client')
77
+ }
78
+ let exp = Number(c.exp)
79
+ if (!(exp * 1000 > (expect.now ?? Date.now()))) throw refused('expired')
80
+ if (typeof c.sub != 'string' || !c.sub) throw refused('names nobody')
81
+ let email = typeof c.email == 'string' && c.email.includes('@')
82
+ ? c.email.trim().toLowerCase()
83
+ : undefined
84
+ return {
85
+ issuer: iss,
86
+ subject: c.sub,
87
+ ...email ? { email } : {},
88
+ verified: c.email_verified === true || c.email_verified === 'true',
89
+ ...typeof c.name == 'string' && c.name ? { name: c.name } : {},
90
+ }
91
+ }
package/mod.js ADDED
@@ -0,0 +1,16 @@
1
+ import { toBase64url } from "@yaks/fp";
2
+ export const attempt = (now = Date.now())=>({
3
+ state: crypto.randomUUID(),
4
+ until: now + 10 * 60 * 1000
5
+ });
6
+ /** A verifier's PKCE S256 challenge: its SHA-256, in base64url. */ export const challenge = async (verifier)=>toBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
7
+ /** PKCE S256; verifier is never sent in the authorization URL. */ export const pkce = async ()=>{
8
+ const verifier = toBase64url(crypto.getRandomValues(new Uint8Array(32)));
9
+ return {
10
+ verifier,
11
+ challenge: await challenge(verifier)
12
+ };
13
+ };
14
+ export { client, OAuthError } from "./client.js";
15
+ export { claims, identity } from "./identity.js";
16
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA,SAAS,WAAW,wBAA6B;AAajD,OAAO,MAAM,UAAU,CAAC,MAAc,KAAK,GAAG,EAAE,GAAc,CAAC;IAC7D,OAAO,OAAO,UAAU;IACxB,OAAO,MAAM,KAAK,KAAK;EACzB,CAAC,EAAC;AACF,iEAAiE,GACjE,OAAO,MAAM,YAAY,OAAO,WAC9B,YACE,IAAI,WACF,MAAM,OAAO,MAAM,CAAC,MAAM,CAAC,WAAW,IAAI,cAAc,MAAM,CAAC,aAElE;AACH,gEAAgE,GAChE,OAAO,MAAM,OAAO;EAGlB,MAAM,WAAW,YAAY,OAAO,eAAe,CAAC,IAAI,WAAW;EACnE,OAAO;IAAE;IAAU,WAAW,MAAM,UAAU;EAAU;AAC1D,EAAC;AACD,SAEE,MAAM,EACN,UAAU,sBAIQ;AACpB,SAAS,MAAM,EAA8B,QAAQ,wBAAuB"}
package/mod.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { toBase64url } from '@yaks/fp'
2
+
3
+ /** Shared private authorization storage, expiring browser-flow attempts, and
4
+ * the generic authorization-code client for a provider described as data
5
+ * (./client.ts). Protocols that are not that flow — MCP discovery, OpenRouter's
6
+ * key exchange — stay in their own adapters.
7
+ */
8
+ export type AuthorizationStore<R extends object> = {
9
+ read(key: string): Promise<R | undefined>
10
+ update<T>(key: string, fn: (record: R) => Promise<T>): Promise<T>
11
+ }
12
+ /** One attempt. Identity checks prevent late exchanges saving after cancellation. */
13
+ export type Attempt = { state: string; until: number; verifier?: string }
14
+ export const attempt = (now: number = Date.now()): Attempt => ({
15
+ state: crypto.randomUUID(),
16
+ until: now + 10 * 60 * 1000,
17
+ })
18
+ /** A verifier's PKCE S256 challenge: its SHA-256, in base64url. */
19
+ export const challenge = async (verifier: string): Promise<string> =>
20
+ toBase64url(
21
+ new Uint8Array(
22
+ await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)),
23
+ ),
24
+ )
25
+ /** PKCE S256; verifier is never sent in the authorization URL. */
26
+ export const pkce = async (): Promise<
27
+ { verifier: string; challenge: string }
28
+ > => {
29
+ const verifier = toBase64url(crypto.getRandomValues(new Uint8Array(32)))
30
+ return { verifier, challenge: await challenge(verifier) }
31
+ }
32
+ export {
33
+ type Client,
34
+ client,
35
+ OAuthError,
36
+ type Options,
37
+ type Provider,
38
+ type Tokens,
39
+ } from './client.js'
40
+ export { claims, type Expect, type Identity, identity } from './identity.js'
package/package.json CHANGED
@@ -1,6 +1,18 @@
1
1
  {
2
2
  "name": "@yaks/oauth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/oauth",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ }
11
+ },
12
+ "license": "Apache-2.0",
13
+ "dependencies": {
14
+ "@yaks/fp": "0.2.36"
15
+ },
16
+ "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.",
17
+ "repository": "https://github.com/yak-sh/yak.git"
18
+ }