nextidp 0.0.1 → 0.1.2
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 +85 -0
- package/README.md +434 -4
- package/dist/cjs/access-token.d.ts +56 -0
- package/dist/cjs/access-token.js +196 -0
- package/dist/cjs/config.d.ts +128 -0
- package/dist/cjs/config.js +233 -0
- package/dist/cjs/cookies.d.ts +23 -0
- package/dist/cjs/cookies.js +118 -0
- package/dist/cjs/discovery.d.ts +24 -0
- package/dist/cjs/discovery.js +91 -0
- package/dist/cjs/errors.d.ts +63 -0
- package/dist/cjs/errors.js +69 -0
- package/dist/cjs/express.d.ts +71 -0
- package/dist/cjs/express.js +114 -0
- package/dist/cjs/http.d.ts +10 -0
- package/dist/cjs/http.js +68 -0
- package/dist/cjs/id-token.d.ts +19 -0
- package/dist/cjs/id-token.js +77 -0
- package/dist/cjs/idp.d.ts +81 -0
- package/dist/cjs/idp.js +482 -0
- package/dist/cjs/index.d.ts +9 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/logout-token.d.ts +13 -0
- package/dist/cjs/logout-token.js +63 -0
- package/dist/cjs/nestjs.d.ts +53 -0
- package/dist/cjs/nestjs.js +142 -0
- package/dist/cjs/next.d.ts +61 -0
- package/dist/cjs/next.js +118 -0
- package/dist/cjs/node-adapter.d.ts +16 -0
- package/dist/cjs/node-adapter.js +76 -0
- package/dist/cjs/node-http.d.ts +22 -0
- package/dist/cjs/node-http.js +127 -0
- package/dist/cjs/node.d.ts +50 -0
- package/dist/cjs/node.js +57 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pkce.d.ts +6 -0
- package/dist/cjs/pkce.js +49 -0
- package/dist/cjs/return-path.d.ts +6 -0
- package/dist/cjs/return-path.js +41 -0
- package/dist/cjs/sealed.d.ts +12 -0
- package/dist/cjs/sealed.js +78 -0
- package/dist/cjs/service.d.ts +61 -0
- package/dist/cjs/service.js +173 -0
- package/dist/cjs/session.d.ts +51 -0
- package/dist/cjs/session.js +97 -0
- package/dist/cjs/store.d.ts +58 -0
- package/dist/cjs/store.js +145 -0
- package/dist/cjs/tokens.d.ts +38 -0
- package/dist/cjs/tokens.js +138 -0
- package/dist/esm/access-token.d.ts +56 -0
- package/dist/esm/access-token.js +156 -0
- package/dist/esm/config.d.ts +128 -0
- package/dist/esm/config.js +206 -0
- package/dist/esm/cookies.d.ts +23 -0
- package/dist/esm/cookies.js +89 -0
- package/dist/esm/discovery.d.ts +24 -0
- package/dist/esm/discovery.js +56 -0
- package/dist/esm/errors.d.ts +63 -0
- package/dist/esm/errors.js +41 -0
- package/dist/esm/express.d.ts +71 -0
- package/dist/esm/express.js +90 -0
- package/dist/esm/http.d.ts +10 -0
- package/dist/esm/http.js +44 -0
- package/dist/esm/id-token.d.ts +19 -0
- package/dist/esm/id-token.js +51 -0
- package/dist/esm/idp.d.ts +81 -0
- package/dist/esm/idp.js +488 -0
- package/dist/esm/index.d.ts +9 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/logout-token.d.ts +13 -0
- package/dist/esm/logout-token.js +39 -0
- package/dist/esm/nestjs.d.ts +53 -0
- package/dist/esm/nestjs.js +118 -0
- package/dist/esm/next.d.ts +61 -0
- package/dist/esm/next.js +94 -0
- package/dist/esm/node-adapter.d.ts +16 -0
- package/dist/esm/node-adapter.js +60 -0
- package/dist/esm/node-http.d.ts +22 -0
- package/dist/esm/node-http.js +96 -0
- package/dist/esm/node.d.ts +50 -0
- package/dist/esm/node.js +33 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pkce.d.ts +6 -0
- package/dist/esm/pkce.js +23 -0
- package/dist/esm/return-path.d.ts +6 -0
- package/dist/esm/return-path.js +17 -0
- package/dist/esm/sealed.d.ts +12 -0
- package/dist/esm/sealed.js +54 -0
- package/dist/esm/service.d.ts +61 -0
- package/dist/esm/service.js +148 -0
- package/dist/esm/session.d.ts +51 -0
- package/dist/esm/session.js +58 -0
- package/dist/esm/store.d.ts +58 -0
- package/dist/esm/store.js +119 -0
- package/dist/esm/tokens.d.ts +38 -0
- package/dist/esm/tokens.js +100 -0
- package/package.json +130 -5
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { JWTPayload } from "jose";
|
|
2
|
+
import * as v from "valibot";
|
|
3
|
+
export declare const FLOW_PURPOSE = "nextidp:flow";
|
|
4
|
+
export declare const SESSION_PURPOSE = "nextidp:session";
|
|
5
|
+
/** A sign-in in progress lasts as long as the auth server's signed request: 10 minutes. */
|
|
6
|
+
export declare const FLOW_MAX_AGE = 600;
|
|
7
|
+
declare const FlowSchema: v.ObjectSchema<{
|
|
8
|
+
readonly verifier: v.StringSchema<undefined>;
|
|
9
|
+
readonly state: v.StringSchema<undefined>;
|
|
10
|
+
readonly nonce: v.StringSchema<undefined>;
|
|
11
|
+
readonly returnTo: v.StringSchema<undefined>;
|
|
12
|
+
}, undefined>;
|
|
13
|
+
export type Flow = v.InferOutput<typeof FlowSchema>;
|
|
14
|
+
export declare function parseFlow(payload: unknown): Flow | undefined;
|
|
15
|
+
declare const StoredSessionSchema: v.ObjectSchema<{
|
|
16
|
+
readonly claims: v.RecordSchema<v.StringSchema<undefined>, v.UnknownSchema, undefined>;
|
|
17
|
+
readonly accessToken: v.StringSchema<undefined>;
|
|
18
|
+
/** Seconds since the epoch. */
|
|
19
|
+
readonly accessTokenExpiresAt: v.NumberSchema<undefined>;
|
|
20
|
+
readonly refreshToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
21
|
+
/** As received: the hint when signing out of the auth server too. */
|
|
22
|
+
readonly idToken: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
23
|
+
readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
24
|
+
}, undefined>;
|
|
25
|
+
export type StoredSession = v.InferOutput<typeof StoredSessionSchema>;
|
|
26
|
+
export declare function parseStoredSession(payload: unknown): StoredSession | undefined;
|
|
27
|
+
/** The person signed in, from the ID token's standard claims. */
|
|
28
|
+
export type IdpUser = {
|
|
29
|
+
/** The `sub` claim: stable for this person at this auth server. */
|
|
30
|
+
id: string;
|
|
31
|
+
email?: string;
|
|
32
|
+
emailVerified?: boolean;
|
|
33
|
+
name?: string;
|
|
34
|
+
picture?: string;
|
|
35
|
+
};
|
|
36
|
+
/** A signed-in session, as the app reads it. The refresh token stays inside nextidp. */
|
|
37
|
+
export type Session = {
|
|
38
|
+
user: IdpUser;
|
|
39
|
+
/** Every claim of the ID token, checked. */
|
|
40
|
+
claims: JWTPayload;
|
|
41
|
+
/** For calling APIs as this person: `Authorization: Bearer <accessToken>`. */
|
|
42
|
+
accessToken: string;
|
|
43
|
+
/** When the access token expires, in seconds since the epoch. */
|
|
44
|
+
accessTokenExpiresAt: number;
|
|
45
|
+
/** The scopes the auth server granted, when it said. */
|
|
46
|
+
scope: string | undefined;
|
|
47
|
+
/** Whether there's a refresh token: `offline_access` was granted. */
|
|
48
|
+
canRefresh: boolean;
|
|
49
|
+
};
|
|
50
|
+
export declare function toSession(stored: StoredSession): Session;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var session_exports = {};
|
|
30
|
+
__export(session_exports, {
|
|
31
|
+
FLOW_MAX_AGE: () => FLOW_MAX_AGE,
|
|
32
|
+
FLOW_PURPOSE: () => FLOW_PURPOSE,
|
|
33
|
+
SESSION_PURPOSE: () => SESSION_PURPOSE,
|
|
34
|
+
parseFlow: () => parseFlow,
|
|
35
|
+
parseStoredSession: () => parseStoredSession,
|
|
36
|
+
toSession: () => toSession
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(session_exports);
|
|
39
|
+
var v = __toESM(require("valibot"), 1);
|
|
40
|
+
const FLOW_PURPOSE = "nextidp:flow";
|
|
41
|
+
const SESSION_PURPOSE = "nextidp:session";
|
|
42
|
+
const FLOW_MAX_AGE = 600;
|
|
43
|
+
const FlowSchema = v.object({
|
|
44
|
+
verifier: v.string(),
|
|
45
|
+
state: v.string(),
|
|
46
|
+
nonce: v.string(),
|
|
47
|
+
returnTo: v.string()
|
|
48
|
+
});
|
|
49
|
+
function parseFlow(payload) {
|
|
50
|
+
const parsed = v.safeParse(FlowSchema, payload);
|
|
51
|
+
return parsed.success ? parsed.output : void 0;
|
|
52
|
+
}
|
|
53
|
+
const StoredSessionSchema = v.object({
|
|
54
|
+
claims: v.record(v.string(), v.unknown()),
|
|
55
|
+
accessToken: v.string(),
|
|
56
|
+
/** Seconds since the epoch. */
|
|
57
|
+
accessTokenExpiresAt: v.number(),
|
|
58
|
+
refreshToken: v.optional(v.string()),
|
|
59
|
+
/** As received: the hint when signing out of the auth server too. */
|
|
60
|
+
idToken: v.optional(v.string()),
|
|
61
|
+
scope: v.optional(v.string())
|
|
62
|
+
});
|
|
63
|
+
function parseStoredSession(payload) {
|
|
64
|
+
const parsed = v.safeParse(StoredSessionSchema, payload);
|
|
65
|
+
return parsed.success ? parsed.output : void 0;
|
|
66
|
+
}
|
|
67
|
+
function text(value) {
|
|
68
|
+
return typeof value === "string" && value ? value : void 0;
|
|
69
|
+
}
|
|
70
|
+
function toSession(stored) {
|
|
71
|
+
const claims = stored.claims;
|
|
72
|
+
const user = { id: String(claims.sub ?? "") };
|
|
73
|
+
const email = text(claims.email);
|
|
74
|
+
const name = text(claims.name);
|
|
75
|
+
const picture = text(claims.picture);
|
|
76
|
+
if (email) user.email = email;
|
|
77
|
+
if (typeof claims.email_verified === "boolean") user.emailVerified = claims.email_verified;
|
|
78
|
+
if (name) user.name = name;
|
|
79
|
+
if (picture) user.picture = picture;
|
|
80
|
+
return {
|
|
81
|
+
user,
|
|
82
|
+
claims,
|
|
83
|
+
accessToken: stored.accessToken,
|
|
84
|
+
accessTokenExpiresAt: stored.accessTokenExpiresAt,
|
|
85
|
+
scope: stored.scope,
|
|
86
|
+
canRefresh: Boolean(stored.refreshToken)
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
90
|
+
0 && (module.exports = {
|
|
91
|
+
FLOW_MAX_AGE,
|
|
92
|
+
FLOW_PURPOSE,
|
|
93
|
+
SESSION_PURPOSE,
|
|
94
|
+
parseFlow,
|
|
95
|
+
parseStoredSession,
|
|
96
|
+
toSession
|
|
97
|
+
});
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type CookieJar } from "./cookies.js";
|
|
2
|
+
import type { Sealer } from "./sealed.js";
|
|
3
|
+
import { type StoredSession } from "./session.js";
|
|
4
|
+
/**
|
|
5
|
+
* Somewhere to keep sessions: Redis, a database table, or `memoryStore()` for one process.
|
|
6
|
+
* Values are strings nextidp has already encrypted. `set` must expire the key after
|
|
7
|
+
* `ttlSeconds`; `get` answers undefined (or null) for a key that's missing or expired.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const store: SessionStore = {
|
|
11
|
+
* get: (key) => redis.get(key),
|
|
12
|
+
* set: async (key, value, ttlSeconds) => { await redis.set(key, value, "EX", ttlSeconds); },
|
|
13
|
+
* delete: async (key) => { await redis.del(key); },
|
|
14
|
+
* };
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export type SessionStore = {
|
|
18
|
+
get(key: string): Promise<string | null | undefined>;
|
|
19
|
+
set(key: string, value: string, ttlSeconds: number): Promise<void>;
|
|
20
|
+
delete(key: string): Promise<void>;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* A store in this process's memory: for development, tests and single-instance apps. Every
|
|
24
|
+
* session is lost on a restart, and instances don't share it.
|
|
25
|
+
*/
|
|
26
|
+
export declare function memoryStore(): SessionStore;
|
|
27
|
+
/** A session as read: the store's id and when it began, when it lives in a store. */
|
|
28
|
+
export type Loaded = {
|
|
29
|
+
stored: StoredSession;
|
|
30
|
+
id?: string;
|
|
31
|
+
createdAt?: number;
|
|
32
|
+
};
|
|
33
|
+
/** What ends sessions from the auth server's side: its session, or every one of a person. */
|
|
34
|
+
export type IdpLogout = {
|
|
35
|
+
sid?: string | undefined;
|
|
36
|
+
sub?: string | undefined;
|
|
37
|
+
};
|
|
38
|
+
export type SessionBackend = {
|
|
39
|
+
load(jar: CookieJar): Promise<Loaded | undefined>;
|
|
40
|
+
/** A new session, after a sign-in: in a store, any session the cookie named is removed. */
|
|
41
|
+
create(jar: CookieJar, stored: StoredSession): Promise<string[]>;
|
|
42
|
+
/** The same session with new tokens, after a refresh. */
|
|
43
|
+
update(jar: CookieJar, loaded: Loaded, stored: StoredSession): Promise<string[]>;
|
|
44
|
+
remove(jar: CookieJar): Promise<string[]>;
|
|
45
|
+
/** Back-channel logout; only with a store. */
|
|
46
|
+
endIdpSession?: (logout: IdpLogout) => Promise<void>;
|
|
47
|
+
};
|
|
48
|
+
type Settings = {
|
|
49
|
+
sealer: Sealer;
|
|
50
|
+
cookie: string;
|
|
51
|
+
secure: boolean;
|
|
52
|
+
maxAge: number;
|
|
53
|
+
clientId: string;
|
|
54
|
+
};
|
|
55
|
+
/** The session in its cookie, as before any store. */
|
|
56
|
+
export declare function cookieBackend(settings: Settings): SessionBackend;
|
|
57
|
+
export declare function storeBackend(store: SessionStore, settings: Settings): SessionBackend;
|
|
58
|
+
export {};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var store_exports = {};
|
|
20
|
+
__export(store_exports, {
|
|
21
|
+
cookieBackend: () => cookieBackend,
|
|
22
|
+
memoryStore: () => memoryStore,
|
|
23
|
+
storeBackend: () => storeBackend
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(store_exports);
|
|
26
|
+
var import_cookies = require("./cookies.js");
|
|
27
|
+
var import_pkce = require("./pkce.js");
|
|
28
|
+
var import_session = require("./session.js");
|
|
29
|
+
function memoryStore() {
|
|
30
|
+
const values = /* @__PURE__ */ new Map();
|
|
31
|
+
const sweep = (now) => {
|
|
32
|
+
for (const [key, entry] of values) if (entry.until <= now) values.delete(key);
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
async get(key) {
|
|
36
|
+
const entry = values.get(key);
|
|
37
|
+
if (!entry) return void 0;
|
|
38
|
+
if (entry.until > Date.now()) return entry.value;
|
|
39
|
+
values.delete(key);
|
|
40
|
+
return void 0;
|
|
41
|
+
},
|
|
42
|
+
async set(key, value, ttlSeconds) {
|
|
43
|
+
const now = Date.now();
|
|
44
|
+
if (values.size >= 1e4) sweep(now);
|
|
45
|
+
values.set(key, { value, until: now + ttlSeconds * 1e3 });
|
|
46
|
+
},
|
|
47
|
+
async delete(key) {
|
|
48
|
+
values.delete(key);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function cookieBackend(settings) {
|
|
53
|
+
const { sealer, cookie, secure, maxAge } = settings;
|
|
54
|
+
const write = async (jar, stored) => (0, import_cookies.writeCookie)(jar, cookie, await sealer.seal(stored, import_session.SESSION_PURPOSE, maxAge), {
|
|
55
|
+
secure,
|
|
56
|
+
maxAge
|
|
57
|
+
});
|
|
58
|
+
return {
|
|
59
|
+
async load(jar) {
|
|
60
|
+
const stored = (0, import_session.parseStoredSession)(
|
|
61
|
+
await sealer.unseal((0, import_cookies.readCookie)(jar, cookie), import_session.SESSION_PURPOSE)
|
|
62
|
+
);
|
|
63
|
+
return stored ? { stored } : void 0;
|
|
64
|
+
},
|
|
65
|
+
create: write,
|
|
66
|
+
update: (jar, _loaded, stored) => write(jar, stored),
|
|
67
|
+
async remove(jar) {
|
|
68
|
+
return (0, import_cookies.clearCookie)(jar, cookie, secure);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const REFERENCE_PURPOSE = "nextidp:session-reference";
|
|
73
|
+
const RECORD_PURPOSE = "nextidp:stored-session";
|
|
74
|
+
function nowSeconds() {
|
|
75
|
+
return Math.floor(Date.now() / 1e3);
|
|
76
|
+
}
|
|
77
|
+
function storeBackend(store, settings) {
|
|
78
|
+
const { sealer, cookie, secure, maxAge } = settings;
|
|
79
|
+
const prefix = `nextidp:${encodeURIComponent(settings.clientId)}`;
|
|
80
|
+
const sessionKey = (id) => `${prefix}:session:${id}`;
|
|
81
|
+
const sidKey = (sid) => `${prefix}:ended-sid:${encodeURIComponent(sid)}`;
|
|
82
|
+
const subKey = (sub) => `${prefix}:ended-sub:${encodeURIComponent(sub)}`;
|
|
83
|
+
const referenced = async (jar) => {
|
|
84
|
+
const reference = await sealer.unseal((0, import_cookies.readCookie)(jar, cookie), REFERENCE_PURPOSE);
|
|
85
|
+
return typeof reference?.id === "string" ? reference.id : void 0;
|
|
86
|
+
};
|
|
87
|
+
const save = async (jar, id, stored, createdAt) => {
|
|
88
|
+
await store.set(
|
|
89
|
+
sessionKey(id),
|
|
90
|
+
await sealer.seal({ ...stored, createdAt }, RECORD_PURPOSE, maxAge),
|
|
91
|
+
maxAge
|
|
92
|
+
);
|
|
93
|
+
return (0, import_cookies.writeCookie)(jar, cookie, await sealer.seal({ id }, REFERENCE_PURPOSE, maxAge), {
|
|
94
|
+
secure,
|
|
95
|
+
maxAge
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
const ended = async (stored, createdAt) => {
|
|
99
|
+
const { sid, sub } = stored.claims;
|
|
100
|
+
if (typeof sid === "string" && sid && await store.get(sidKey(sid))) return true;
|
|
101
|
+
if (typeof sub !== "string" || !sub) return false;
|
|
102
|
+
const since = Number(await store.get(subKey(sub)));
|
|
103
|
+
return Number.isFinite(since) && since >= createdAt;
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
async load(jar) {
|
|
107
|
+
const id = await referenced(jar);
|
|
108
|
+
if (!id) return void 0;
|
|
109
|
+
const sealed = await store.get(sessionKey(id));
|
|
110
|
+
if (!sealed) return void 0;
|
|
111
|
+
const payload = await sealer.unseal(sealed, RECORD_PURPOSE);
|
|
112
|
+
const stored = (0, import_session.parseStoredSession)(payload);
|
|
113
|
+
const createdAt = typeof payload?.createdAt === "number" ? payload.createdAt : 0;
|
|
114
|
+
if (!stored) return void 0;
|
|
115
|
+
if (await ended(stored, createdAt)) {
|
|
116
|
+
await store.delete(sessionKey(id));
|
|
117
|
+
return void 0;
|
|
118
|
+
}
|
|
119
|
+
return { stored, id, createdAt };
|
|
120
|
+
},
|
|
121
|
+
async create(jar, stored) {
|
|
122
|
+
const previous = await referenced(jar);
|
|
123
|
+
if (previous) await store.delete(sessionKey(previous));
|
|
124
|
+
return save(jar, (0, import_pkce.randomToken)(), stored, nowSeconds());
|
|
125
|
+
},
|
|
126
|
+
update(jar, loaded, stored) {
|
|
127
|
+
return save(jar, loaded.id ?? (0, import_pkce.randomToken)(), stored, loaded.createdAt ?? nowSeconds());
|
|
128
|
+
},
|
|
129
|
+
async remove(jar) {
|
|
130
|
+
const id = await referenced(jar);
|
|
131
|
+
if (id) await store.delete(sessionKey(id));
|
|
132
|
+
return (0, import_cookies.clearCookie)(jar, cookie, secure);
|
|
133
|
+
},
|
|
134
|
+
async endIdpSession({ sid, sub }) {
|
|
135
|
+
if (sid) await store.set(sidKey(sid), "1", maxAge);
|
|
136
|
+
else if (sub) await store.set(subKey(sub), String(nowSeconds()), maxAge);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
141
|
+
0 && (module.exports = {
|
|
142
|
+
cookieBackend,
|
|
143
|
+
memoryStore,
|
|
144
|
+
storeBackend
|
|
145
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
import type { Discovery } from "./discovery.js";
|
|
3
|
+
import type { Http } from "./http.js";
|
|
4
|
+
declare const TokenResponseSchema: v.ObjectSchema<{
|
|
5
|
+
readonly access_token: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.NonEmptyAction<string, undefined>]>;
|
|
6
|
+
readonly token_type: v.StringSchema<undefined>;
|
|
7
|
+
readonly expires_in: v.OptionalSchema<v.NumberSchema<undefined>, undefined>;
|
|
8
|
+
readonly id_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
9
|
+
readonly refresh_token: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
10
|
+
readonly scope: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
|
|
11
|
+
}, undefined>;
|
|
12
|
+
export type TokenResponse = v.InferOutput<typeof TokenResponseSchema>;
|
|
13
|
+
export type Client = {
|
|
14
|
+
clientId: string;
|
|
15
|
+
clientSecret: string | undefined;
|
|
16
|
+
};
|
|
17
|
+
/** Redeems an authorization code, proving with the PKCE verifier that this app asked for it. */
|
|
18
|
+
export declare function exchangeCode(http: Http, discovery: Discovery, client: Client, input: {
|
|
19
|
+
code: string;
|
|
20
|
+
verifier: string;
|
|
21
|
+
redirectUri: string;
|
|
22
|
+
resource: string | undefined;
|
|
23
|
+
}): Promise<TokenResponse>;
|
|
24
|
+
/** New tokens for a refresh token. The server rotates it: the old one stops working. */
|
|
25
|
+
export declare function refreshTokens(http: Http, discovery: Discovery, client: Client, input: {
|
|
26
|
+
refreshToken: string;
|
|
27
|
+
resource: string | undefined;
|
|
28
|
+
}): Promise<TokenResponse>;
|
|
29
|
+
/** A service's own access token (RFC 6749 4.4): no person, the client's own credentials. */
|
|
30
|
+
export declare function clientCredentials(http: Http, discovery: Discovery, client: Client, input: {
|
|
31
|
+
scope: string | undefined;
|
|
32
|
+
resource: string | undefined;
|
|
33
|
+
}): Promise<TokenResponse>;
|
|
34
|
+
/** Revokes a refresh token at sign-out, when the server offers revocation. Never throws. */
|
|
35
|
+
export declare function revokeRefreshToken(http: Http, discovery: Discovery, client: Client, refreshToken: string): Promise<void>;
|
|
36
|
+
/** The userinfo endpoint's claims for an access token. */
|
|
37
|
+
export declare function fetchUserInfo(http: Http, discovery: Discovery, accessToken: string): Promise<Record<string, unknown>>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var tokens_exports = {};
|
|
30
|
+
__export(tokens_exports, {
|
|
31
|
+
clientCredentials: () => clientCredentials,
|
|
32
|
+
exchangeCode: () => exchangeCode,
|
|
33
|
+
fetchUserInfo: () => fetchUserInfo,
|
|
34
|
+
refreshTokens: () => refreshTokens,
|
|
35
|
+
revokeRefreshToken: () => revokeRefreshToken
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(tokens_exports);
|
|
38
|
+
var v = __toESM(require("valibot"), 1);
|
|
39
|
+
var import_errors = require("./errors.js");
|
|
40
|
+
const TokenResponseSchema = v.object({
|
|
41
|
+
access_token: v.pipe(v.string(), v.nonEmpty()),
|
|
42
|
+
token_type: v.string(),
|
|
43
|
+
expires_in: v.optional(v.number()),
|
|
44
|
+
id_token: v.optional(v.string()),
|
|
45
|
+
refresh_token: v.optional(v.string()),
|
|
46
|
+
scope: v.optional(v.string())
|
|
47
|
+
});
|
|
48
|
+
function authenticate(client, form) {
|
|
49
|
+
if (!client.clientSecret) {
|
|
50
|
+
form.set("client_id", client.clientId);
|
|
51
|
+
return {};
|
|
52
|
+
}
|
|
53
|
+
const pair = `${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`;
|
|
54
|
+
return { authorization: `Basic ${btoa(pair)}` };
|
|
55
|
+
}
|
|
56
|
+
function oauthError(data) {
|
|
57
|
+
const error = data?.error;
|
|
58
|
+
return typeof error === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(error) ? error : void 0;
|
|
59
|
+
}
|
|
60
|
+
async function tokenRequest(http, discovery, client, form, code) {
|
|
61
|
+
const headers = authenticate(client, form);
|
|
62
|
+
let answer;
|
|
63
|
+
try {
|
|
64
|
+
answer = await http.postForm(discovery.token_endpoint, form, headers);
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
throw new import_errors.IdpError(code, "The token endpoint didn't answer.", { cause });
|
|
67
|
+
}
|
|
68
|
+
if (!answer.ok) {
|
|
69
|
+
throw new import_errors.IdpError(
|
|
70
|
+
code,
|
|
71
|
+
`The token endpoint refused: ${oauthError(answer.data) ?? answer.status}.`,
|
|
72
|
+
{ status: answer.status }
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
const parsed = v.safeParse(TokenResponseSchema, answer.data);
|
|
76
|
+
if (!parsed.success) throw new import_errors.IdpError(code, "The token endpoint's answer isn't valid.");
|
|
77
|
+
return parsed.output;
|
|
78
|
+
}
|
|
79
|
+
function exchangeCode(http, discovery, client, input) {
|
|
80
|
+
const form = new URLSearchParams({
|
|
81
|
+
grant_type: "authorization_code",
|
|
82
|
+
code: input.code,
|
|
83
|
+
code_verifier: input.verifier,
|
|
84
|
+
redirect_uri: input.redirectUri
|
|
85
|
+
});
|
|
86
|
+
if (input.resource) form.set("resource", input.resource);
|
|
87
|
+
return tokenRequest(http, discovery, client, form, "token_failed");
|
|
88
|
+
}
|
|
89
|
+
function refreshTokens(http, discovery, client, input) {
|
|
90
|
+
const form = new URLSearchParams({
|
|
91
|
+
grant_type: "refresh_token",
|
|
92
|
+
refresh_token: input.refreshToken
|
|
93
|
+
});
|
|
94
|
+
if (input.resource) form.set("resource", input.resource);
|
|
95
|
+
return tokenRequest(http, discovery, client, form, "refresh_failed");
|
|
96
|
+
}
|
|
97
|
+
function clientCredentials(http, discovery, client, input) {
|
|
98
|
+
const form = new URLSearchParams({ grant_type: "client_credentials" });
|
|
99
|
+
if (input.scope) form.set("scope", input.scope);
|
|
100
|
+
if (input.resource) form.set("resource", input.resource);
|
|
101
|
+
return tokenRequest(http, discovery, client, form, "service_token_failed");
|
|
102
|
+
}
|
|
103
|
+
async function revokeRefreshToken(http, discovery, client, refreshToken) {
|
|
104
|
+
if (!discovery.revocation_endpoint) return;
|
|
105
|
+
const form = new URLSearchParams({ token: refreshToken, token_type_hint: "refresh_token" });
|
|
106
|
+
const headers = authenticate(client, form);
|
|
107
|
+
await http.postForm(discovery.revocation_endpoint, form, headers).catch(() => void 0);
|
|
108
|
+
}
|
|
109
|
+
async function fetchUserInfo(http, discovery, accessToken) {
|
|
110
|
+
if (!discovery.userinfo_endpoint) {
|
|
111
|
+
throw new import_errors.IdpError("userinfo_failed", "The auth server has no userinfo endpoint.");
|
|
112
|
+
}
|
|
113
|
+
let answer;
|
|
114
|
+
try {
|
|
115
|
+
answer = await http.get(discovery.userinfo_endpoint, {
|
|
116
|
+
authorization: `Bearer ${accessToken}`
|
|
117
|
+
});
|
|
118
|
+
} catch (cause) {
|
|
119
|
+
throw new import_errors.IdpError("userinfo_failed", "The userinfo endpoint didn't answer.", { cause });
|
|
120
|
+
}
|
|
121
|
+
if (!answer.ok) {
|
|
122
|
+
throw new import_errors.IdpError("userinfo_failed", `The userinfo endpoint answered ${answer.status}.`, {
|
|
123
|
+
status: answer.status
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (!answer.data || typeof answer.data !== "object" || Array.isArray(answer.data)) {
|
|
127
|
+
throw new import_errors.IdpError("userinfo_failed", "The userinfo answer isn't an object.");
|
|
128
|
+
}
|
|
129
|
+
return answer.data;
|
|
130
|
+
}
|
|
131
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
132
|
+
0 && (module.exports = {
|
|
133
|
+
clientCredentials,
|
|
134
|
+
exchangeCode,
|
|
135
|
+
fetchUserInfo,
|
|
136
|
+
refreshTokens,
|
|
137
|
+
revokeRefreshToken
|
|
138
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type JWTVerifyGetKey } from "jose";
|
|
2
|
+
import type { ApiConfig } from "./config.js";
|
|
3
|
+
import type { Discovery } from "./discovery.js";
|
|
4
|
+
import { IdpError } from "./errors.js";
|
|
5
|
+
import type { Http } from "./http.js";
|
|
6
|
+
/** An access token that checked out. */
|
|
7
|
+
export type AccessToken = {
|
|
8
|
+
/** `sub`: the person, or for a service calling as itself, its client ID. */
|
|
9
|
+
subject: string | undefined;
|
|
10
|
+
/** The app the token was issued to. */
|
|
11
|
+
clientId: string | undefined;
|
|
12
|
+
/** A service calling as itself (client credentials), not on a person's behalf. */
|
|
13
|
+
isService: boolean;
|
|
14
|
+
scopes: string[];
|
|
15
|
+
audience: string[];
|
|
16
|
+
/** Seconds since the epoch. */
|
|
17
|
+
expiresAt: number | undefined;
|
|
18
|
+
/** Every claim, or every field of the introspection answer. */
|
|
19
|
+
claims: Record<string, unknown>;
|
|
20
|
+
};
|
|
21
|
+
export type TokenRequirements = {
|
|
22
|
+
/** Every one of these scopes must be granted. */
|
|
23
|
+
scopes?: readonly string[] | undefined;
|
|
24
|
+
};
|
|
25
|
+
/** The token in an `Authorization: Bearer …` header, or undefined. */
|
|
26
|
+
export declare function bearerToken(authorization: string | null | undefined): string | undefined;
|
|
27
|
+
/** Throws insufficient_scope (403) unless every required scope was granted. */
|
|
28
|
+
export declare function requireScopes(token: AccessToken, required?: readonly string[]): AccessToken;
|
|
29
|
+
/** Whether a token is a JWT (three parts, a header that decodes) rather than opaque. */
|
|
30
|
+
export declare function isJwt(token: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* A JWT access token (RFC 9068): `typ` at+jwt, so no other kind of JWT (an ID token, a logout
|
|
33
|
+
* token) passes for one; a signature by one of the issuer's keys (asymmetric algorithms
|
|
34
|
+
* only); `iss`; `aud` naming this API; and not expired (60 seconds of clock skew).
|
|
35
|
+
*/
|
|
36
|
+
export declare function verifyJwtAccessToken(token: string, keys: JWTVerifyGetKey, config: Pick<ApiConfig, "issuer" | "audience">): Promise<AccessToken>;
|
|
37
|
+
/**
|
|
38
|
+
* Asks the auth server whether an opaque token is active, with this API's client
|
|
39
|
+
* credentials. The auth server answers only for tokens this client issued, or tokens for an
|
|
40
|
+
* API this client is linked to; to anything else it answers inactive.
|
|
41
|
+
*/
|
|
42
|
+
export declare function introspect(http: Http, discovery: Discovery, config: ApiConfig, token: string): Promise<AccessToken>;
|
|
43
|
+
/**
|
|
44
|
+
* The WWW-Authenticate challenge for a refused request (RFC 6750 3): no error code when
|
|
45
|
+
* there was no token at all, else invalid_token or insufficient_scope with the scopes needed.
|
|
46
|
+
*/
|
|
47
|
+
export declare function bearerChallenge(error: IdpError): string;
|
|
48
|
+
/** The status, challenge and JSON body to answer a refused request with. */
|
|
49
|
+
export declare function tokenRefusal(error: IdpError): {
|
|
50
|
+
status: 401 | 403;
|
|
51
|
+
headers: Record<string, string>;
|
|
52
|
+
body: {
|
|
53
|
+
error: string;
|
|
54
|
+
error_description: string;
|
|
55
|
+
};
|
|
56
|
+
};
|