houdini 1.2.10 → 1.2.12

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 (59) hide show
  1. package/build/cmd-cjs/index.js +1539 -16157
  2. package/build/cmd-esm/index.js +1541 -16159
  3. package/build/codegen/transforms/collectDefinitions.d.ts +1 -1
  4. package/build/codegen/utils/flattenSelections.d.ts +1 -1
  5. package/build/codegen-cjs/index.js +301 -14970
  6. package/build/codegen-esm/index.js +305 -14974
  7. package/build/lib/config.d.ts +4 -0
  8. package/build/lib/index.d.ts +1 -1
  9. package/build/lib/types.d.ts +2 -2
  10. package/build/lib-cjs/index.js +1600 -15892
  11. package/build/lib-esm/index.js +1596 -15894
  12. package/build/{lib/router → router}/conventions.d.ts +2 -1
  13. package/build/{lib/router → router}/index.d.ts +2 -0
  14. package/build/router/manifest.d.ts +12 -0
  15. package/build/router/server.d.ts +4 -0
  16. package/build/{lib/router → router}/types.d.ts +3 -2
  17. package/build/router-cjs/index.js +57736 -0
  18. package/build/router-cjs/package.json +1 -0
  19. package/build/router-esm/index.js +57726 -0
  20. package/build/router-esm/package.json +1 -0
  21. package/build/runtime/client/documentStore.d.ts +1 -0
  22. package/build/runtime/client/index.d.ts +14 -2
  23. package/build/runtime/lib/config.d.ts +19 -0
  24. package/build/runtime/lib/types.d.ts +39 -0
  25. package/build/runtime/router/cookies.d.ts +41 -0
  26. package/build/runtime/router/jwt.d.ts +117 -0
  27. package/build/runtime/router/server.d.ts +25 -0
  28. package/build/runtime-cjs/client/documentStore.d.ts +1 -0
  29. package/build/runtime-cjs/client/documentStore.js +42 -2
  30. package/build/runtime-cjs/client/index.d.ts +14 -2
  31. package/build/runtime-cjs/client/index.js +8 -2
  32. package/build/runtime-cjs/lib/config.d.ts +19 -0
  33. package/build/runtime-cjs/lib/config.js +10 -0
  34. package/build/runtime-cjs/lib/types.d.ts +39 -0
  35. package/build/runtime-cjs/router/cookies.d.ts +41 -0
  36. package/build/runtime-cjs/router/cookies.js +168 -0
  37. package/build/runtime-cjs/router/jwt.d.ts +117 -0
  38. package/build/runtime-cjs/router/jwt.js +181 -0
  39. package/build/runtime-cjs/router/server.d.ts +25 -0
  40. package/build/runtime-cjs/router/server.js +78 -0
  41. package/build/runtime-esm/client/documentStore.d.ts +1 -0
  42. package/build/runtime-esm/client/documentStore.js +42 -2
  43. package/build/runtime-esm/client/index.d.ts +14 -2
  44. package/build/runtime-esm/client/index.js +8 -2
  45. package/build/runtime-esm/lib/config.d.ts +19 -0
  46. package/build/runtime-esm/lib/config.js +8 -0
  47. package/build/runtime-esm/lib/types.d.ts +39 -0
  48. package/build/runtime-esm/router/cookies.d.ts +41 -0
  49. package/build/runtime-esm/router/cookies.js +143 -0
  50. package/build/runtime-esm/router/jwt.d.ts +117 -0
  51. package/build/runtime-esm/router/jwt.js +155 -0
  52. package/build/runtime-esm/router/server.d.ts +25 -0
  53. package/build/runtime-esm/router/server.js +53 -0
  54. package/build/test-cjs/index.js +324 -14973
  55. package/build/test-esm/index.js +328 -14977
  56. package/build/vite-cjs/index.js +1826 -16184
  57. package/build/vite-esm/index.js +1828 -16186
  58. package/package.json +10 -1
  59. package/build/lib/router/manifest.d.ts +0 -45
@@ -1,3 +1,4 @@
1
+ import { getCurrentConfig, localApiEndpoint } from "../lib";
1
2
  import { flatten } from "../lib/flatten";
2
3
  import { DocumentStore } from "./documentStore";
3
4
  import {
@@ -15,13 +16,14 @@ class HoudiniClient {
15
16
  url;
16
17
  plugins;
17
18
  throwOnError_operations;
19
+ proxies = {};
18
20
  constructor({
19
21
  url,
20
22
  fetchParams,
21
23
  plugins,
22
24
  pipeline,
23
25
  throwOnError
24
- }) {
26
+ } = {}) {
25
27
  if (plugins && pipeline) {
26
28
  throw new Error(
27
29
  "A client cannot be given a pipeline and a list of plugins at the same time."
@@ -43,7 +45,8 @@ class HoudiniClient {
43
45
  )
44
46
  )
45
47
  );
46
- this.url = url;
48
+ let serverPort = globalThis.process?.env?.HOUDINI_PORT ?? "5173";
49
+ this.url = url ?? (globalThis.window ? "" : `https://localhost:${serverPort}`) + localApiEndpoint(getCurrentConfig());
47
50
  }
48
51
  observe({
49
52
  enableCache = true,
@@ -58,6 +61,9 @@ class HoudiniClient {
58
61
  ...rest
59
62
  });
60
63
  }
64
+ registerProxy(url, handler) {
65
+ this.proxies[url] = handler;
66
+ }
61
67
  }
62
68
  function createPluginHooks(plugins) {
63
69
  return plugins.reduce((hooks, plugin) => {
@@ -5,6 +5,8 @@ export declare function setMockConfig(config: ConfigFile | null): void;
5
5
  export declare function defaultConfigValues(file: ConfigFile): ConfigFile;
6
6
  export declare function keyFieldsForType(configFile: ConfigFile, type: string): string[];
7
7
  export declare function computeID(configFile: ConfigFile, type: string, data: any): string;
8
+ export declare function localApiEndpoint(configFile: ConfigFile): string;
9
+ export declare function localApiSessionKeys(configFile: ConfigFile): string[];
8
10
  export declare function getCurrentConfig(): ConfigFile;
9
11
  export type ConfigFile = {
10
12
  /**
@@ -110,6 +112,23 @@ export type ConfigFile = {
110
112
  * you must enable this flag.
111
113
  */
112
114
  acceptImperativeInstability?: boolean;
115
+ /**
116
+ * Configure the router
117
+ */
118
+ router?: RouterConfig;
119
+ };
120
+ type RouterConfig = {
121
+ auth?: AuthStrategy;
122
+ apiEndpoint?: string;
123
+ };
124
+ type AuthStrategy = {
125
+ redirect: string;
126
+ sessionKeys: string[];
127
+ url: string;
128
+ } | {
129
+ mutation: string;
130
+ sessionKeys: string[];
131
+ url: string;
113
132
  };
114
133
  type ScalarMap = {
115
134
  [typeName: string]: ScalarSpec;
@@ -36,6 +36,12 @@ function computeID(configFile, type, data) {
36
36
  return id.slice(0, -2);
37
37
  }
38
38
  let _configFile = null;
39
+ function localApiEndpoint(configFile) {
40
+ return configFile.router?.apiEndpoint ?? "/_api";
41
+ }
42
+ function localApiSessionKeys(configFile) {
43
+ return configFile.router?.auth?.sessionKeys ?? [];
44
+ }
39
45
  function getCurrentConfig() {
40
46
  const mockConfig2 = getMockConfig();
41
47
  if (mockConfig2) {
@@ -57,5 +63,7 @@ export {
57
63
  getCurrentConfig,
58
64
  getMockConfig,
59
65
  keyFieldsForType,
66
+ localApiEndpoint,
67
+ localApiSessionKeys,
60
68
  setMockConfig
61
69
  };
@@ -317,4 +317,43 @@ interface VariableNode {
317
317
  export declare const PendingValue: unique symbol;
318
318
  export type LoadingType = typeof PendingValue;
319
319
  export declare function isPending(value: any): value is LoadingType;
320
+ export type ProjectManifest = {
321
+ /** All of the pages in the project */
322
+ pages: Record<string, PageManifest>;
323
+ /** All of the layouts in the project */
324
+ layouts: Record<string, PageManifest>;
325
+ /** All of the page queries in the project */
326
+ page_queries: Record<string, QueryManifest>;
327
+ /** All of the layout queries in the project */
328
+ layout_queries: Record<string, QueryManifest>;
329
+ /** All of the artifacts in the project */
330
+ artifacts: string[];
331
+ /** Whether or not there is a local schema defined */
332
+ local_schema: boolean;
333
+ /** Whether or not there is a custom instance of yoga defined */
334
+ local_yoga: boolean;
335
+ };
336
+ export type PageManifest = {
337
+ id: string;
338
+ /** the name of every query that the page depends on */
339
+ queries: string[];
340
+ /** the list of queries that this page could potentially ask for */
341
+ query_options: string[];
342
+ /** the full url pattern of the page */
343
+ url: string;
344
+ /** the ids of layouts that wrap this page */
345
+ layouts: string[];
346
+ /** The filepath of the unit */
347
+ path: string;
348
+ };
349
+ export type QueryManifest = {
350
+ /** the name of the query */
351
+ name: string;
352
+ /** the url tied with the query */
353
+ url: string;
354
+ /** wether the query uses the loading directive (ie, wants a fallback) */
355
+ loading: boolean;
356
+ /** The filepath of the unit */
357
+ path: string;
358
+ };
320
359
  export {};
@@ -0,0 +1,41 @@
1
+ /*!
2
+ * cookie
3
+ * Copyright(c) 2012-2014 Roman Shtylman
4
+ * Copyright(c) 2015 Douglas Christopher Wilson
5
+ * MIT Licensed
6
+ */
7
+ /**
8
+ * Parse a cookie header.
9
+ *
10
+ * Parse the given cookie header string into an object
11
+ * The object has the various cookies as keys(names) => values
12
+ *
13
+ * @param {string} str
14
+ * @param {object} [options]
15
+ * @return {object}
16
+ * @public
17
+ */
18
+ export declare function parse(str: string, options?: {
19
+ decode?: (val: string) => string;
20
+ }): Record<string, string>;
21
+ /**
22
+ * Serialize data into a cookie header.
23
+ *
24
+ * Serialize the a name value pair into a cookie string suitable for
25
+ * http headers. An optional options object specified cookie parameters.
26
+ *
27
+ * serialize('foo', 'bar', { httpOnly: true })
28
+ * => "foo=bar; httpOnly"
29
+ *
30
+ */
31
+ export declare function serialize(name: string, val: string, options: {
32
+ encode: boolean;
33
+ maxAge: number;
34
+ domain: string;
35
+ path: string;
36
+ expires: Date;
37
+ httpOnly: boolean;
38
+ priority: string | number;
39
+ secure: boolean;
40
+ sameSite: string | boolean;
41
+ }): string;
@@ -0,0 +1,143 @@
1
+ /*!
2
+ * cookie
3
+ * Copyright(c) 2012-2014 Roman Shtylman
4
+ * Copyright(c) 2015 Douglas Christopher Wilson
5
+ * MIT Licensed
6
+ */
7
+ let __toString = Object.prototype.toString;
8
+ let fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
9
+ function parse(str, options) {
10
+ if (typeof str !== "string") {
11
+ throw new TypeError("argument str must be a string");
12
+ }
13
+ let obj = {};
14
+ let opt = options || {};
15
+ let dec = opt.decode || decode;
16
+ let index = 0;
17
+ while (index < str.length) {
18
+ let eqIdx = str.indexOf("=", index);
19
+ if (eqIdx === -1) {
20
+ break;
21
+ }
22
+ let endIdx = str.indexOf(";", index);
23
+ if (endIdx === -1) {
24
+ endIdx = str.length;
25
+ } else if (endIdx < eqIdx) {
26
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
27
+ continue;
28
+ }
29
+ let key = str.slice(index, eqIdx).trim();
30
+ if (void 0 === obj[key]) {
31
+ let val = str.slice(eqIdx + 1, endIdx).trim();
32
+ if (val.charCodeAt(0) === 34) {
33
+ val = val.slice(1, -1);
34
+ }
35
+ obj[key] = tryDecode(val, dec);
36
+ }
37
+ index = endIdx + 1;
38
+ }
39
+ return obj;
40
+ }
41
+ function serialize(name, val, options) {
42
+ let opt = options || {};
43
+ let enc = opt.encode || encode;
44
+ if (typeof enc !== "function") {
45
+ throw new TypeError("option encode is invalid");
46
+ }
47
+ if (!fieldContentRegExp.test(name)) {
48
+ throw new TypeError("argument name is invalid");
49
+ }
50
+ let value = enc(val);
51
+ if (value && !fieldContentRegExp.test(value)) {
52
+ throw new TypeError("argument val is invalid");
53
+ }
54
+ let str = name + "=" + value;
55
+ if (opt.maxAge !== null) {
56
+ let maxAge = opt.maxAge - 0;
57
+ if (Number.isNaN(maxAge) || !isFinite(maxAge)) {
58
+ throw new TypeError("option maxAge is invalid");
59
+ }
60
+ str += "; Max-Age=" + Math.floor(maxAge);
61
+ }
62
+ if (opt.domain) {
63
+ if (!fieldContentRegExp.test(opt.domain)) {
64
+ throw new TypeError("option domain is invalid");
65
+ }
66
+ str += "; Domain=" + opt.domain;
67
+ }
68
+ if (opt.path) {
69
+ if (!fieldContentRegExp.test(opt.path)) {
70
+ throw new TypeError("option path is invalid");
71
+ }
72
+ str += "; Path=" + opt.path;
73
+ }
74
+ if (opt.expires) {
75
+ let expires = opt.expires;
76
+ if (!isDate(expires) || Number.isNaN(expires.valueOf())) {
77
+ throw new TypeError("option expires is invalid");
78
+ }
79
+ str += "; Expires=" + expires.toUTCString();
80
+ }
81
+ if (opt.httpOnly) {
82
+ str += "; HttpOnly";
83
+ }
84
+ if (opt.secure) {
85
+ str += "; Secure";
86
+ }
87
+ if (opt.priority) {
88
+ let priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
89
+ switch (priority) {
90
+ case "low":
91
+ str += "; Priority=Low";
92
+ break;
93
+ case "medium":
94
+ str += "; Priority=Medium";
95
+ break;
96
+ case "high":
97
+ str += "; Priority=High";
98
+ break;
99
+ default:
100
+ throw new TypeError("option priority is invalid");
101
+ }
102
+ }
103
+ if (opt.sameSite) {
104
+ let sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
105
+ switch (sameSite) {
106
+ case true:
107
+ str += "; SameSite=Strict";
108
+ break;
109
+ case "lax":
110
+ str += "; SameSite=Lax";
111
+ break;
112
+ case "strict":
113
+ str += "; SameSite=Strict";
114
+ break;
115
+ case "none":
116
+ str += "; SameSite=None";
117
+ break;
118
+ default:
119
+ throw new TypeError("option sameSite is invalid");
120
+ }
121
+ }
122
+ return str;
123
+ }
124
+ function decode(str) {
125
+ return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
126
+ }
127
+ function encode(val) {
128
+ return encodeURIComponent(val);
129
+ }
130
+ function isDate(val) {
131
+ return __toString.call(val) === "[object Date]" || val instanceof Date;
132
+ }
133
+ function tryDecode(str, decode2) {
134
+ try {
135
+ return decode2(str);
136
+ } catch (e) {
137
+ return str;
138
+ }
139
+ }
140
+ export {
141
+ parse,
142
+ serialize
143
+ };
@@ -0,0 +1,117 @@
1
+ type SubtleCryptoImportKeyAlgorithm = any;
2
+ /**
3
+ * @typedef JwtAlgorithm
4
+ * @type {'ES256'|'ES384'|'ES512'|'HS256'|'HS384'|'HS512'|'RS256'|'RS384'|'RS512'}
5
+ */
6
+ export type JwtAlgorithm = 'ES256' | 'ES384' | 'ES512' | 'HS256' | 'HS384' | 'HS512' | 'RS256' | 'RS384' | 'RS512';
7
+ /**
8
+ * @typedef JwtAlgorithms
9
+ */
10
+ export interface JwtAlgorithms {
11
+ [key: string]: SubtleCryptoImportKeyAlgorithm;
12
+ }
13
+ /**
14
+ * @typedef JwtHeader
15
+ * @prop {string} [typ] Type
16
+ */
17
+ export interface JwtHeader {
18
+ /**
19
+ * Type (default: `"JWT"`)
20
+ *
21
+ * @default "JWT"
22
+ */
23
+ typ?: string;
24
+ [key: string]: any;
25
+ }
26
+ /**
27
+ * @typedef JwtPayload
28
+ * @prop {string} [iss] Issuer
29
+ * @prop {string} [sub] Subject
30
+ * @prop {string | string[]} [aud] Audience
31
+ * @prop {string} [exp] Expiration Time
32
+ * @prop {string} [nbf] Not Before
33
+ * @prop {string} [iat] Issued At
34
+ * @prop {string} [jti] JWT ID
35
+ */
36
+ export interface JwtPayload {
37
+ /** Issuer */
38
+ iss?: string;
39
+ /** Subject */
40
+ sub?: string;
41
+ /** Audience */
42
+ aud?: string | string[];
43
+ /** Expiration Time */
44
+ exp?: number;
45
+ /** Not Before */
46
+ nbf?: number;
47
+ /** Issued At */
48
+ iat?: number;
49
+ /** JWT ID */
50
+ jti?: string;
51
+ [key: string]: any;
52
+ }
53
+ /**
54
+ * @typedef JwtOptions
55
+ * @prop {JwtAlgorithm | string} algorithm
56
+ */
57
+ export interface JwtOptions {
58
+ algorithm?: JwtAlgorithm | string;
59
+ }
60
+ /**
61
+ * @typedef JwtSignOptions
62
+ * @extends JwtOptions
63
+ * @prop {JwtHeader} [header]
64
+ */
65
+ export interface JwtSignOptions extends JwtOptions {
66
+ header?: JwtHeader;
67
+ }
68
+ /**
69
+ * @typedef JwtVerifyOptions
70
+ * @extends JwtOptions
71
+ * @prop {boolean} [throwError=false] If `true` throw error if checks fail. (default: `false`)
72
+ */
73
+ export interface JwtVerifyOptions extends JwtOptions {
74
+ /**
75
+ * If `true` throw error if checks fail. (default: `false`)
76
+ *
77
+ * @default false
78
+ */
79
+ throwError?: boolean;
80
+ }
81
+ /**
82
+ * @typedef JwtData
83
+ * @prop {JwtHeader} header
84
+ * @prop {JwtPayload} payload
85
+ */
86
+ export interface JwtData {
87
+ header: JwtHeader;
88
+ payload: JwtPayload;
89
+ }
90
+ /**
91
+ * Signs a payload and returns the token
92
+ *
93
+ * @param {JwtPayload} payload The payload object. To use `nbf` (Not Before) and/or `exp` (Expiration Time) add `nbf` and/or `exp` to the payload.
94
+ * @param {string | JsonWebKey} secret A string which is used to sign the payload.
95
+ * @param {JwtSignOptions | JwtAlgorithm | string} [options={ algorithm: 'HS256', header: { typ: 'JWT' } }] The options object or the algorithm.
96
+ * @throws {Error} If there's a validation issue.
97
+ * @returns {Promise<string>} Returns token as a `string`.
98
+ */
99
+ export declare function encode(payload: JwtPayload, secret: string | JsonWebKey, options?: JwtSignOptions | JwtAlgorithm): Promise<string>;
100
+ /**
101
+ * Verifies the integrity of the token and returns a boolean value.
102
+ *
103
+ * @param {string} token The token string generated by `jwt.sign()`.
104
+ * @param {string | JsonWebKey} secret The string which was used to sign the payload.
105
+ * @param {JWTVerifyOptions | JWTAlgorithm} options The options object or the algorithm.
106
+ * @throws {Error | string} Throws an error `string` if the token is invalid or an `Error-Object` if there's a validation issue.
107
+ * @returns {Promise<boolean>} Returns `true` if signature, `nbf` (if set) and `exp` (if set) are valid, otherwise returns `false`.
108
+ */
109
+ export declare function verify(token: string, secret: string | JsonWebKey, options?: JwtVerifyOptions | JwtAlgorithm): Promise<boolean>;
110
+ /**
111
+ * Returns the payload **without** verifying the integrity of the token. Please use `jwt.verify()` first to keep your application secure!
112
+ *
113
+ * @param {string} token The token string generated by `jwt.sign()`.
114
+ * @returns {JwtData} Returns an `object` containing `header` and `payload`.
115
+ */
116
+ export declare function decode(token: string): JwtData;
117
+ export {};
@@ -0,0 +1,155 @@
1
+ function base64UrlParse(s) {
2
+ return new Uint8Array(
3
+ Array.prototype.map.call(
4
+ atob(s.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, "")),
5
+ (c) => c.charCodeAt(0)
6
+ )
7
+ );
8
+ }
9
+ function base64UrlStringify(a) {
10
+ return btoa(String.fromCharCode.apply(0, a)).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
11
+ }
12
+ const algorithms = {
13
+ ES256: { name: "ECDSA", namedCurve: "P-256", hash: { name: "SHA-256" } },
14
+ ES384: { name: "ECDSA", namedCurve: "P-384", hash: { name: "SHA-384" } },
15
+ ES512: { name: "ECDSA", namedCurve: "P-521", hash: { name: "SHA-512" } },
16
+ HS256: { name: "HMAC", hash: { name: "SHA-256" } },
17
+ HS384: { name: "HMAC", hash: { name: "SHA-384" } },
18
+ HS512: { name: "HMAC", hash: { name: "SHA-512" } },
19
+ RS256: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } },
20
+ RS384: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-384" } },
21
+ RS512: { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-512" } }
22
+ };
23
+ function _utf8ToUint8Array(str) {
24
+ return base64UrlParse(btoa(unescape(encodeURIComponent(str))));
25
+ }
26
+ function _str2ab(str) {
27
+ str = atob(str);
28
+ const buf = new ArrayBuffer(str.length);
29
+ const bufView = new Uint8Array(buf);
30
+ for (let i = 0, strLen = str.length; i < strLen; i++) {
31
+ bufView[i] = str.charCodeAt(i);
32
+ }
33
+ return buf;
34
+ }
35
+ function _decodePayload(raw) {
36
+ switch (raw.length % 4) {
37
+ case 0:
38
+ break;
39
+ case 2:
40
+ raw += "==";
41
+ break;
42
+ case 3:
43
+ raw += "=";
44
+ break;
45
+ default:
46
+ throw new Error("Illegal base64url string!");
47
+ }
48
+ try {
49
+ return JSON.parse(decodeURIComponent(escape(atob(raw))));
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ async function encode(payload, secret, options = { algorithm: "HS256", header: { typ: "JWT" } }) {
55
+ if (typeof options === "string")
56
+ options = { algorithm: options, header: { typ: "JWT" } };
57
+ options = { algorithm: "HS256", header: { typ: "JWT" }, ...options };
58
+ if (payload === null || typeof payload !== "object")
59
+ throw new Error("payload must be an object");
60
+ if (typeof secret !== "string" && typeof secret !== "object")
61
+ throw new Error("secret must be a string or a JWK object");
62
+ if (typeof options.algorithm !== "string")
63
+ throw new Error("options.algorithm must be a string");
64
+ const algorithm = algorithms[options.algorithm];
65
+ if (!algorithm)
66
+ throw new Error("algorithm not found");
67
+ if (!payload.iat)
68
+ payload.iat = Math.floor(Date.now() / 1e3);
69
+ const payloadAsJSON = JSON.stringify(payload);
70
+ const partialToken = `${base64UrlStringify(
71
+ _utf8ToUint8Array(JSON.stringify({ ...options.header, alg: options.algorithm }))
72
+ )}.${base64UrlStringify(_utf8ToUint8Array(payloadAsJSON))}`;
73
+ let keyFormat = "raw";
74
+ let keyData;
75
+ if (typeof secret === "object") {
76
+ keyFormat = "jwk";
77
+ keyData = secret;
78
+ } else if (typeof secret === "string" && secret.startsWith("-----BEGIN")) {
79
+ keyFormat = "pkcs8";
80
+ keyData = _str2ab(
81
+ secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, "")
82
+ );
83
+ } else
84
+ keyData = _utf8ToUint8Array(secret);
85
+ const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ["sign"]);
86
+ const signature = await crypto.subtle.sign(algorithm, key, _utf8ToUint8Array(partialToken));
87
+ return `${partialToken}.${base64UrlStringify(new Uint8Array(signature))}`;
88
+ }
89
+ async function verify(token, secret, options = { algorithm: "HS256", throwError: false }) {
90
+ if (typeof options === "string")
91
+ options = { algorithm: options, throwError: false };
92
+ options = { algorithm: "HS256", throwError: false, ...options };
93
+ if (typeof token !== "string")
94
+ throw new Error("token must be a string");
95
+ if (typeof secret !== "string" && typeof secret !== "object")
96
+ throw new Error("secret must be a string or a JWK object");
97
+ if (typeof options.algorithm !== "string")
98
+ throw new Error("options.algorithm must be a string");
99
+ const tokenParts = token.split(".");
100
+ if (tokenParts.length !== 3)
101
+ throw new Error("token must consist of 3 parts");
102
+ const algorithm = algorithms[options.algorithm];
103
+ if (!algorithm)
104
+ throw new Error("algorithm not found");
105
+ const { payload } = decode(token);
106
+ if (!payload) {
107
+ if (options.throwError)
108
+ throw "PARSE_ERROR";
109
+ return false;
110
+ }
111
+ if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1e3)) {
112
+ if (options.throwError)
113
+ throw "NOT_YET_VALID";
114
+ return false;
115
+ }
116
+ if (payload.exp && payload.exp <= Math.floor(Date.now() / 1e3)) {
117
+ if (options.throwError)
118
+ throw "EXPIRED";
119
+ return false;
120
+ }
121
+ let keyFormat = "raw";
122
+ let keyData;
123
+ if (typeof secret === "object") {
124
+ keyFormat = "jwk";
125
+ keyData = secret;
126
+ } else if (typeof secret === "string" && secret.startsWith("-----BEGIN")) {
127
+ keyFormat = "spki";
128
+ keyData = _str2ab(
129
+ secret.replace(/-----BEGIN.*?-----/g, "").replace(/-----END.*?-----/g, "").replace(/\s/g, "")
130
+ );
131
+ } else
132
+ keyData = _utf8ToUint8Array(secret);
133
+ const key = await crypto.subtle.importKey(keyFormat, keyData, algorithm, false, ["verify"]);
134
+ return await crypto.subtle.verify(
135
+ algorithm,
136
+ key,
137
+ base64UrlParse(tokenParts[2]),
138
+ _utf8ToUint8Array(`${tokenParts[0]}.${tokenParts[1]}`)
139
+ );
140
+ }
141
+ function decode(token) {
142
+ return {
143
+ header: _decodePayload(
144
+ token.split(".")[0].replace(/-/g, "+").replace(/_/g, "/")
145
+ ),
146
+ payload: _decodePayload(
147
+ token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/")
148
+ )
149
+ };
150
+ }
151
+ export {
152
+ decode,
153
+ encode,
154
+ verify
155
+ };
@@ -0,0 +1,25 @@
1
+ import type { ConfigFile } from '../lib';
2
+ type ServerHandlerArgs = {
3
+ url: string;
4
+ config: ConfigFile;
5
+ session_keys: string[];
6
+ set_header: (key: string, value: string | number | string[]) => void;
7
+ get_header: (key: string) => string | number | string[] | undefined;
8
+ redirect: (code: number, url: string) => void;
9
+ next: () => void;
10
+ };
11
+ export declare function handle_request(args: ServerHandlerArgs): Promise<void>;
12
+ export type Server = {
13
+ use(fn: ServerMiddleware): void;
14
+ };
15
+ export type ServerMiddleware = (req: IncomingRequest, res: ServerResponse, next: () => void) => void;
16
+ export type IncomingRequest = {
17
+ url?: string;
18
+ headers: Headers;
19
+ };
20
+ export type ServerResponse = {
21
+ redirect(url: string, status?: number): void;
22
+ set_header(name: string, value: string): void;
23
+ };
24
+ export declare function get_session(req: Headers, secrets: string[]): Promise<App.Session>;
25
+ export {};
@@ -0,0 +1,53 @@
1
+ import { parse } from "./cookies";
2
+ import { decode, encode, verify } from "./jwt";
3
+ async function handle_request(args) {
4
+ const plugin_config = args.config.router ?? {};
5
+ if (plugin_config.auth && "redirect" in plugin_config.auth && args.url.startsWith(plugin_config.auth.redirect)) {
6
+ return await redirect_auth(args);
7
+ }
8
+ args.next();
9
+ }
10
+ async function redirect_auth(args) {
11
+ const { searchParams } = new URL(args.url, `http://${args.get_header("host")}`);
12
+ const { redirectTo, ...session } = Object.fromEntries(searchParams.entries());
13
+ await set_session(args, session);
14
+ if (redirectTo) {
15
+ return args.redirect(302, redirectTo);
16
+ }
17
+ args.next();
18
+ }
19
+ const session_cookie_name = "__houdini__";
20
+ async function set_session(req, value) {
21
+ const today = new Date();
22
+ const expires = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1e3);
23
+ const serialized = await encode(value, req.session_keys[0]);
24
+ req.set_header(
25
+ "Set-Cookie",
26
+ `${session_cookie_name}=${serialized}; Path=/; HttpOnly; Secure; SameSite=Lax; Expires=${expires.toUTCString()} `
27
+ );
28
+ }
29
+ async function get_session(req, secrets) {
30
+ const cookies = req.get("cookie");
31
+ if (!cookies) {
32
+ return {};
33
+ }
34
+ const cookie = parse(cookies)[session_cookie_name];
35
+ if (!cookie) {
36
+ return {};
37
+ }
38
+ for (const secret of secrets) {
39
+ if (!await verify(cookie, secret)) {
40
+ continue;
41
+ }
42
+ const parsed = decode(cookie);
43
+ if (!parsed) {
44
+ return {};
45
+ }
46
+ return parsed.payload;
47
+ }
48
+ return {};
49
+ }
50
+ export {
51
+ get_session,
52
+ handle_request
53
+ };