nextidp 0.0.1 → 0.1.3

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.
Files changed (101) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +502 -4
  3. package/dist/cjs/access-token.d.ts +56 -0
  4. package/dist/cjs/access-token.js +196 -0
  5. package/dist/cjs/config.d.ts +128 -0
  6. package/dist/cjs/config.js +233 -0
  7. package/dist/cjs/cookies.d.ts +23 -0
  8. package/dist/cjs/cookies.js +118 -0
  9. package/dist/cjs/discovery.d.ts +24 -0
  10. package/dist/cjs/discovery.js +91 -0
  11. package/dist/cjs/errors.d.ts +63 -0
  12. package/dist/cjs/errors.js +69 -0
  13. package/dist/cjs/express.d.ts +71 -0
  14. package/dist/cjs/express.js +114 -0
  15. package/dist/cjs/hono.d.ts +65 -0
  16. package/dist/cjs/hono.js +130 -0
  17. package/dist/cjs/http.d.ts +10 -0
  18. package/dist/cjs/http.js +68 -0
  19. package/dist/cjs/id-token.d.ts +19 -0
  20. package/dist/cjs/id-token.js +77 -0
  21. package/dist/cjs/idp.d.ts +81 -0
  22. package/dist/cjs/idp.js +482 -0
  23. package/dist/cjs/index.d.ts +9 -0
  24. package/dist/cjs/index.js +53 -0
  25. package/dist/cjs/logout-token.d.ts +13 -0
  26. package/dist/cjs/logout-token.js +63 -0
  27. package/dist/cjs/nestjs.d.ts +53 -0
  28. package/dist/cjs/nestjs.js +142 -0
  29. package/dist/cjs/next.d.ts +61 -0
  30. package/dist/cjs/next.js +118 -0
  31. package/dist/cjs/node-adapter.d.ts +16 -0
  32. package/dist/cjs/node-adapter.js +76 -0
  33. package/dist/cjs/node-http.d.ts +22 -0
  34. package/dist/cjs/node-http.js +127 -0
  35. package/dist/cjs/node.d.ts +50 -0
  36. package/dist/cjs/node.js +57 -0
  37. package/dist/cjs/package.json +1 -0
  38. package/dist/cjs/pkce.d.ts +6 -0
  39. package/dist/cjs/pkce.js +49 -0
  40. package/dist/cjs/return-path.d.ts +6 -0
  41. package/dist/cjs/return-path.js +41 -0
  42. package/dist/cjs/sealed.d.ts +12 -0
  43. package/dist/cjs/sealed.js +78 -0
  44. package/dist/cjs/service.d.ts +61 -0
  45. package/dist/cjs/service.js +173 -0
  46. package/dist/cjs/session.d.ts +51 -0
  47. package/dist/cjs/session.js +97 -0
  48. package/dist/cjs/store.d.ts +58 -0
  49. package/dist/cjs/store.js +145 -0
  50. package/dist/cjs/tokens.d.ts +38 -0
  51. package/dist/cjs/tokens.js +138 -0
  52. package/dist/esm/access-token.d.ts +56 -0
  53. package/dist/esm/access-token.js +156 -0
  54. package/dist/esm/config.d.ts +128 -0
  55. package/dist/esm/config.js +206 -0
  56. package/dist/esm/cookies.d.ts +23 -0
  57. package/dist/esm/cookies.js +89 -0
  58. package/dist/esm/discovery.d.ts +24 -0
  59. package/dist/esm/discovery.js +56 -0
  60. package/dist/esm/errors.d.ts +63 -0
  61. package/dist/esm/errors.js +41 -0
  62. package/dist/esm/express.d.ts +71 -0
  63. package/dist/esm/express.js +90 -0
  64. package/dist/esm/hono.d.ts +65 -0
  65. package/dist/esm/hono.js +106 -0
  66. package/dist/esm/http.d.ts +10 -0
  67. package/dist/esm/http.js +44 -0
  68. package/dist/esm/id-token.d.ts +19 -0
  69. package/dist/esm/id-token.js +51 -0
  70. package/dist/esm/idp.d.ts +81 -0
  71. package/dist/esm/idp.js +488 -0
  72. package/dist/esm/index.d.ts +9 -0
  73. package/dist/esm/index.js +30 -0
  74. package/dist/esm/logout-token.d.ts +13 -0
  75. package/dist/esm/logout-token.js +39 -0
  76. package/dist/esm/nestjs.d.ts +53 -0
  77. package/dist/esm/nestjs.js +118 -0
  78. package/dist/esm/next.d.ts +61 -0
  79. package/dist/esm/next.js +94 -0
  80. package/dist/esm/node-adapter.d.ts +16 -0
  81. package/dist/esm/node-adapter.js +60 -0
  82. package/dist/esm/node-http.d.ts +22 -0
  83. package/dist/esm/node-http.js +96 -0
  84. package/dist/esm/node.d.ts +50 -0
  85. package/dist/esm/node.js +33 -0
  86. package/dist/esm/package.json +1 -0
  87. package/dist/esm/pkce.d.ts +6 -0
  88. package/dist/esm/pkce.js +23 -0
  89. package/dist/esm/return-path.d.ts +6 -0
  90. package/dist/esm/return-path.js +17 -0
  91. package/dist/esm/sealed.d.ts +12 -0
  92. package/dist/esm/sealed.js +54 -0
  93. package/dist/esm/service.d.ts +61 -0
  94. package/dist/esm/service.js +148 -0
  95. package/dist/esm/session.d.ts +51 -0
  96. package/dist/esm/session.js +58 -0
  97. package/dist/esm/store.d.ts +58 -0
  98. package/dist/esm/store.js +119 -0
  99. package/dist/esm/tokens.d.ts +38 -0
  100. package/dist/esm/tokens.js +100 -0
  101. package/package.json +152 -5
@@ -0,0 +1,6 @@
1
+ /** 256 random bits, base64url: a PKCE verifier (RFC 7636 4.1), a state or a nonce. */
2
+ export declare function randomToken(): string;
3
+ /** The S256 code challenge for a verifier: base64url(SHA-256(verifier)). */
4
+ export declare function challengeFor(verifier: string): Promise<string>;
5
+ /** Compares two strings without leaking where they differ through timing. */
6
+ export declare function sameString(a: string, b: string): boolean;
@@ -0,0 +1,49 @@
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 pkce_exports = {};
20
+ __export(pkce_exports, {
21
+ challengeFor: () => challengeFor,
22
+ randomToken: () => randomToken,
23
+ sameString: () => sameString
24
+ });
25
+ module.exports = __toCommonJS(pkce_exports);
26
+ var import_jose = require("jose");
27
+ function randomToken() {
28
+ return import_jose.base64url.encode(crypto.getRandomValues(new Uint8Array(32)));
29
+ }
30
+ async function challengeFor(verifier) {
31
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
32
+ return import_jose.base64url.encode(new Uint8Array(digest));
33
+ }
34
+ function sameString(a, b) {
35
+ const left = new TextEncoder().encode(a);
36
+ const right = new TextEncoder().encode(b);
37
+ if (left.length !== right.length) return false;
38
+ let difference = 0;
39
+ for (let index = 0; index < left.length; index += 1) {
40
+ difference |= (left[index] ?? 0) ^ (right[index] ?? 0);
41
+ }
42
+ return difference === 0;
43
+ }
44
+ // Annotate the CommonJS export names for ESM import in node:
45
+ 0 && (module.exports = {
46
+ challengeFor,
47
+ randomToken,
48
+ sameString
49
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A path of this app, or undefined. Where a sign-in returns to comes from the browser
3
+ * (`?returnTo=`, a form field), so anything that could lead to another site is refused:
4
+ * `//evil.example`, `/\evil.example`, `https://…`, `javascript:…`, and control characters.
5
+ */
6
+ export declare function safePath(value: unknown): string | undefined;
@@ -0,0 +1,41 @@
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 return_path_exports = {};
20
+ __export(return_path_exports, {
21
+ safePath: () => safePath
22
+ });
23
+ module.exports = __toCommonJS(return_path_exports);
24
+ const PLACEHOLDER = "http://nextidp.invalid";
25
+ function safePath(value) {
26
+ if (typeof value !== "string" || !value.startsWith("/")) return void 0;
27
+ if (value.startsWith("//") || value.includes("\\") || /[\u0000-\u001f\u007f]/.test(value)) {
28
+ return void 0;
29
+ }
30
+ try {
31
+ const url = new URL(value, PLACEHOLDER);
32
+ if (url.origin !== PLACEHOLDER) return void 0;
33
+ return `${url.pathname}${url.search}${url.hash}`;
34
+ } catch {
35
+ return void 0;
36
+ }
37
+ }
38
+ // Annotate the CommonJS export names for ESM import in node:
39
+ 0 && (module.exports = {
40
+ safePath
41
+ });
@@ -0,0 +1,12 @@
1
+ /** Seals and opens values for one `idp()` instance; derived keys are kept, not recomputed. */
2
+ export declare class Sealer {
3
+ #private;
4
+ constructor(secrets: readonly string[]);
5
+ /** Encrypts with the first secret. */
6
+ seal(payload: Record<string, unknown>, purpose: string, maxAgeSeconds: number): Promise<string>;
7
+ /**
8
+ * The payload, or undefined if the value is missing, altered, sealed for another purpose,
9
+ * expired, or sealed with a secret no longer in the list. Tries every secret, in order.
10
+ */
11
+ unseal(value: string | undefined, purpose: string): Promise<Record<string, unknown> | undefined>;
12
+ }
@@ -0,0 +1,78 @@
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 sealed_exports = {};
20
+ __export(sealed_exports, {
21
+ Sealer: () => Sealer
22
+ });
23
+ module.exports = __toCommonJS(sealed_exports);
24
+ var import_jose = require("jose");
25
+ const encoder = new TextEncoder();
26
+ const SALT = encoder.encode("nextidp sealed cookie");
27
+ async function deriveKey(secret, purpose) {
28
+ const material = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, [
29
+ "deriveBits"
30
+ ]);
31
+ const bits = await crypto.subtle.deriveBits(
32
+ { name: "HKDF", hash: "SHA-256", salt: SALT, info: encoder.encode(purpose) },
33
+ material,
34
+ 256
35
+ );
36
+ return new Uint8Array(bits);
37
+ }
38
+ class Sealer {
39
+ #secrets;
40
+ #keys = /* @__PURE__ */ new Map();
41
+ constructor(secrets) {
42
+ this.#secrets = secrets;
43
+ }
44
+ #key(secret, purpose) {
45
+ const id = `${purpose}\0${secret}`;
46
+ let key = this.#keys.get(id);
47
+ if (!key) {
48
+ key = deriveKey(secret, purpose);
49
+ this.#keys.set(id, key);
50
+ }
51
+ return key;
52
+ }
53
+ /** Encrypts with the first secret. */
54
+ async seal(payload, purpose, maxAgeSeconds) {
55
+ const [secret] = this.#secrets;
56
+ if (secret === void 0) throw new Error("No secret to seal with.");
57
+ return new import_jose.EncryptJWT(payload).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${maxAgeSeconds}s`).encrypt(await this.#key(secret, purpose));
58
+ }
59
+ /**
60
+ * The payload, or undefined if the value is missing, altered, sealed for another purpose,
61
+ * expired, or sealed with a secret no longer in the list. Tries every secret, in order.
62
+ */
63
+ async unseal(value, purpose) {
64
+ if (!value) return void 0;
65
+ for (const secret of this.#secrets) {
66
+ try {
67
+ const { payload } = await (0, import_jose.jwtDecrypt)(value, await this.#key(secret, purpose));
68
+ return payload;
69
+ } catch {
70
+ }
71
+ }
72
+ return void 0;
73
+ }
74
+ }
75
+ // Annotate the CommonJS export names for ESM import in node:
76
+ 0 && (module.exports = {
77
+ Sealer
78
+ });
@@ -0,0 +1,61 @@
1
+ import type { ServiceConfig } from "./config.js";
2
+ import type { Discovery } from "./discovery.js";
3
+ import type { Http } from "./http.js";
4
+ export type ServiceTokenOptions = {
5
+ /** The scopes to ask for (default: none, so the auth server decides). */
6
+ scopes?: readonly string[] | undefined;
7
+ /** The API the token is for (RFC 8707). Default `resource` (IDP_RESOURCE), if set. */
8
+ resource?: string | undefined;
9
+ /** Ask for a new token even if one is kept. */
10
+ fresh?: boolean | undefined;
11
+ };
12
+ export type UseServiceTokenOptions = Omit<ServiceTokenOptions, "fresh"> & {
13
+ /**
14
+ * The origins the token may be sent to, like `https://orders.example.com`. Default: the
15
+ * origin of `resource` (or IDP_RESOURCE). A request anywhere else goes out untouched, with
16
+ * no token: a URL from elsewhere must never carry this service's token away.
17
+ */
18
+ origins?: readonly string[] | undefined;
19
+ };
20
+ type RequestConfigLike = {
21
+ url: string;
22
+ baseUrl?: string;
23
+ headers?: Record<string, string>;
24
+ retried?: boolean;
25
+ };
26
+ /**
27
+ * What `useServiceToken` needs of an HTTP client: fast-http-client's `createHttp()` has it.
28
+ * Written out rather than imported, so a client from another version of it fits too.
29
+ */
30
+ export type InterceptableClient = {
31
+ request(config: RequestConfigLike): Promise<unknown>;
32
+ interceptors: {
33
+ request: {
34
+ use(fn: (config: RequestConfigLike) => Promise<RequestConfigLike>): () => void;
35
+ };
36
+ response: {
37
+ use(handlers: {
38
+ onRejected?: (error: unknown) => unknown;
39
+ }): () => void;
40
+ };
41
+ };
42
+ };
43
+ export type ServiceTokens = {
44
+ get(options?: ServiceTokenOptions): Promise<string>;
45
+ drop(token: string): void;
46
+ /** The API a token is for when a call names none (IDP_RESOURCE). */
47
+ defaultResource: string | undefined;
48
+ };
49
+ export declare function createServiceTokens(deps: {
50
+ http: Http;
51
+ discovery: () => Promise<Discovery>;
52
+ config: ServiceConfig;
53
+ }): ServiceTokens;
54
+ /**
55
+ * Puts a service token on every request of `client` to the allowed origins, and nowhere else.
56
+ * When the API answers 401, the token is dropped and the request sent once more with a new
57
+ * one (a token revoked early); a second 401 is the caller's. Returns a function that takes
58
+ * both hooks off.
59
+ */
60
+ export declare function useServiceToken(tokens: ServiceTokens, client: InterceptableClient, options?: UseServiceTokenOptions): () => void;
61
+ export {};
@@ -0,0 +1,173 @@
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 service_exports = {};
20
+ __export(service_exports, {
21
+ createServiceTokens: () => createServiceTokens,
22
+ useServiceToken: () => useServiceToken
23
+ });
24
+ module.exports = __toCommonJS(service_exports);
25
+ var import_access_token = require("./access-token.js");
26
+ var import_errors = require("./errors.js");
27
+ var import_tokens = require("./tokens.js");
28
+ const RENEW_BEFORE_S = 60;
29
+ const MAX_KEPT = 100;
30
+ function misconfigured(problem) {
31
+ return new import_errors.IdpError("misconfigured", `nextidp is misconfigured: ${problem}.`);
32
+ }
33
+ function scopeOf(scopes) {
34
+ const list = [...new Set((scopes ?? []).map((scope) => scope.trim()).filter(Boolean))];
35
+ if (list.some((scope) => /\s/.test(scope))) throw misconfigured("a scope can't hold spaces");
36
+ return list.length > 0 ? list.sort().join(" ") : void 0;
37
+ }
38
+ function resourceOf(resource) {
39
+ if (resource === void 0) return void 0;
40
+ if (!URL.canParse(resource) || /\s/.test(resource)) {
41
+ throw misconfigured("resource must be an absolute URI");
42
+ }
43
+ return resource;
44
+ }
45
+ function createServiceTokens(deps) {
46
+ const kept = /* @__PURE__ */ new Map();
47
+ const client = { clientId: deps.config.clientId, clientSecret: deps.config.clientSecret };
48
+ const issue = async (scope, resource) => {
49
+ const tokens = await (0, import_tokens.clientCredentials)(deps.http, await deps.discovery(), client, {
50
+ scope,
51
+ resource
52
+ });
53
+ const lifetime = tokens.expires_in ?? 0;
54
+ const renewIn = lifetime - Math.min(RENEW_BEFORE_S, lifetime / 2);
55
+ return { token: tokens.access_token, until: Date.now() + Math.max(0, renewIn) * 1e3 };
56
+ };
57
+ const prune = (now) => {
58
+ for (const [key, entry] of kept) {
59
+ if (entry.issued && entry.issued.until <= now) kept.delete(key);
60
+ }
61
+ const oldest = kept.keys().next();
62
+ if (kept.size >= MAX_KEPT && !oldest.done) kept.delete(oldest.value);
63
+ };
64
+ return {
65
+ async get(options = {}) {
66
+ const scope = scopeOf(options.scopes);
67
+ const resource = resourceOf(options.resource ?? deps.config.resource);
68
+ const key = JSON.stringify([resource ?? null, scope ?? null]);
69
+ const now = Date.now();
70
+ const known = kept.get(key);
71
+ if (known && !options.fresh) {
72
+ if (!known.issued) return (await known.pending).token;
73
+ if (known.issued.until > now) return known.issued.token;
74
+ }
75
+ if (kept.size >= MAX_KEPT) prune(now);
76
+ const entry = { pending: issue(scope, resource) };
77
+ entry.pending.then(
78
+ (issued) => {
79
+ entry.issued = issued;
80
+ },
81
+ () => void 0
82
+ );
83
+ kept.set(key, entry);
84
+ try {
85
+ return (await entry.pending).token;
86
+ } catch (error) {
87
+ if (kept.get(key) === entry) kept.delete(key);
88
+ throw error;
89
+ }
90
+ },
91
+ drop(token) {
92
+ for (const [key, entry] of kept) if (entry.issued?.token === token) kept.delete(key);
93
+ },
94
+ defaultResource: deps.config.resource
95
+ };
96
+ }
97
+ function statusOf(error) {
98
+ const status = error?.status;
99
+ return typeof status === "number" ? status : void 0;
100
+ }
101
+ function configOf(error) {
102
+ const config = error?.config;
103
+ return config && typeof config === "object" && typeof config.url === "string" ? config : void 0;
104
+ }
105
+ function originOf(config) {
106
+ try {
107
+ return new URL(config.url, config.baseUrl).origin;
108
+ } catch {
109
+ return void 0;
110
+ }
111
+ }
112
+ function allowedOrigins(tokens, options) {
113
+ const resource = options.resource ?? tokens.defaultResource;
114
+ const listed = options.origins ?? (resource && /^https?:\/\//i.test(resource) ? [resource] : []);
115
+ const origins = /* @__PURE__ */ new Set();
116
+ for (const value of listed) {
117
+ const url = URL.canParse(value) ? new URL(value) : void 0;
118
+ if (!url || url.protocol !== "https:" && url.protocol !== "http:") {
119
+ throw misconfigured("useServiceToken's origins must be http(s) URLs");
120
+ }
121
+ origins.add(url.origin);
122
+ }
123
+ if (origins.size === 0) {
124
+ throw misconfigured(
125
+ "useServiceToken needs origins, or an http(s) resource, to know where the token may go"
126
+ );
127
+ }
128
+ return origins;
129
+ }
130
+ function withoutAuthorization(headers) {
131
+ return Object.fromEntries(
132
+ Object.entries(headers ?? {}).filter(([name]) => name.toLowerCase() !== "authorization")
133
+ );
134
+ }
135
+ function useServiceToken(tokens, client, options = {}) {
136
+ const origins = allowedOrigins(tokens, options);
137
+ const { origins: _listed, ...tokenOptions } = options;
138
+ const allowed = (config) => {
139
+ const origin = originOf(config);
140
+ return origin !== void 0 && origins.has(origin);
141
+ };
142
+ const stopRequest = client.interceptors.request.use(
143
+ async (config) => allowed(config) ? {
144
+ ...config,
145
+ headers: {
146
+ ...withoutAuthorization(config.headers),
147
+ authorization: `Bearer ${await tokens.get(tokenOptions)}`
148
+ }
149
+ } : config
150
+ );
151
+ const stopResponse = client.interceptors.response.use({
152
+ async onRejected(error) {
153
+ const config = configOf(error);
154
+ if (statusOf(error) !== 401 || !config || config.retried || !allowed(config)) throw error;
155
+ const refused = (0, import_access_token.bearerToken)(
156
+ Object.entries(config.headers ?? {}).find(
157
+ ([name]) => name.toLowerCase() === "authorization"
158
+ )?.[1]
159
+ );
160
+ if (refused) tokens.drop(refused);
161
+ return client.request({ ...config, retried: true });
162
+ }
163
+ });
164
+ return () => {
165
+ stopRequest();
166
+ stopResponse();
167
+ };
168
+ }
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ createServiceTokens,
172
+ useServiceToken
173
+ });
@@ -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 {};