wirejs-resources 0.1.7-alpha → 0.1.9-alpha

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.
@@ -0,0 +1,286 @@
1
+ import { scrypt, randomBytes } from 'crypto';
2
+ import * as jose from 'jose';
3
+ import { Resource } from '../resource.js';
4
+ import { FileService } from './file.js';
5
+ import { Secret } from '../resources/secret.js';
6
+ import { withContext } from '../adapters/context.js';
7
+ import { overrides } from '../overrides.js';
8
+ function hash(password, salt) {
9
+ return new Promise((resolve, reject) => {
10
+ const finalSalt = salt || randomBytes(16).toString('hex');
11
+ scrypt(password, finalSalt, 64, (err, key) => {
12
+ if (err) {
13
+ reject(err);
14
+ }
15
+ else {
16
+ resolve(`${finalSalt}$${key.toString('hex')}`);
17
+ }
18
+ });
19
+ });
20
+ }
21
+ async function verifyHash(password, passwordHash) {
22
+ const [saltPart, _hashPart] = passwordHash.split('$');
23
+ const rehashed = await hash(password, saltPart);
24
+ return rehashed === passwordHash;
25
+ }
26
+ // #endregion
27
+ const ONE_WEEK = 7 * 24 * 60 * 60; // days * hours/day * minutes/hour * seconds/minute
28
+ export class AuthenticationService extends Resource {
29
+ #duration;
30
+ ;
31
+ #keepalive;
32
+ #cookieName;
33
+ #rawSigningSecret;
34
+ #signingSecret;
35
+ #users;
36
+ constructor(scope, id, { duration, keepalive, cookie } = {}) {
37
+ super(scope, id);
38
+ this.#duration = duration || ONE_WEEK;
39
+ this.#keepalive = !!keepalive;
40
+ this.#cookieName = cookie ?? 'identity';
41
+ this.#rawSigningSecret = new (overrides.Secret || Secret)(this, 'jwt-signing-secret');
42
+ const fileService = new (overrides.FileService || FileService)(this, 'files');
43
+ this.#users = {
44
+ id,
45
+ async get(username) {
46
+ try {
47
+ const data = await fileService.read(this.filenameFor(username));
48
+ return JSON.parse(data);
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ },
54
+ async set(username, details) {
55
+ await fileService.write(this.filenameFor(username), JSON.stringify(details));
56
+ },
57
+ async has(username) {
58
+ const user = await this.get(username);
59
+ return !!user;
60
+ },
61
+ filenameFor(username) {
62
+ return `${username}.json`;
63
+ }
64
+ };
65
+ }
66
+ async getSigningSecret() {
67
+ const secretAsString = await this.#rawSigningSecret.read();
68
+ return new TextEncoder().encode(secretAsString);
69
+ }
70
+ get signingSecret() {
71
+ if (!this.#signingSecret) {
72
+ this.#signingSecret = this.getSigningSecret();
73
+ }
74
+ return this.#signingSecret;
75
+ }
76
+ async getBaseState(cookies) {
77
+ let idCookie;
78
+ let user;
79
+ try {
80
+ idCookie = cookies.get(this.#cookieName)?.value;
81
+ const idPayload = idCookie ? (await jose.jwtVerify(idCookie, await this.signingSecret)) : undefined;
82
+ user = idPayload ? idPayload.payload.sub : undefined;
83
+ }
84
+ catch (err) {
85
+ // jose doesn't like our cookie.
86
+ console.error(err);
87
+ }
88
+ if (user) {
89
+ return {
90
+ state: 'authenticated',
91
+ user
92
+ };
93
+ }
94
+ else {
95
+ return {
96
+ state: 'unauthenticated',
97
+ user: undefined,
98
+ };
99
+ }
100
+ }
101
+ async getState(cookies) {
102
+ const state = await this.getBaseState(cookies);
103
+ if (state.state === 'authenticated') {
104
+ if (this.#keepalive)
105
+ this.setBaseState(cookies, state.user);
106
+ return {
107
+ state,
108
+ actions: {
109
+ changepassword: {
110
+ name: "Change Password",
111
+ inputs: {
112
+ existingPassword: {
113
+ label: 'Old Password',
114
+ type: 'password',
115
+ },
116
+ newPassword: {
117
+ label: 'New Password',
118
+ type: 'password',
119
+ }
120
+ },
121
+ buttons: ['Change Password']
122
+ },
123
+ signout: {
124
+ name: "Sign out"
125
+ },
126
+ }
127
+ };
128
+ }
129
+ else {
130
+ return {
131
+ state,
132
+ actions: {
133
+ signin: {
134
+ name: "Sign In",
135
+ inputs: {
136
+ username: {
137
+ label: 'Username',
138
+ type: 'text',
139
+ },
140
+ password: {
141
+ label: 'Password',
142
+ type: 'password',
143
+ },
144
+ },
145
+ buttons: ['Sign In']
146
+ },
147
+ signup: {
148
+ name: "Sign Up",
149
+ inputs: {
150
+ username: {
151
+ label: 'Username',
152
+ type: 'text',
153
+ },
154
+ password: {
155
+ label: 'Password',
156
+ type: 'password',
157
+ },
158
+ },
159
+ buttons: ['Sign Up']
160
+ },
161
+ }
162
+ };
163
+ }
164
+ }
165
+ async setBaseState(cookies, user) {
166
+ if (!user) {
167
+ cookies.delete(this.#cookieName);
168
+ }
169
+ else {
170
+ const jwt = await new jose.SignJWT({})
171
+ .setProtectedHeader({ alg: 'HS256' })
172
+ .setIssuedAt()
173
+ .setSubject(user)
174
+ .setExpirationTime(`${this.#duration}s`)
175
+ .sign(await this.signingSecret);
176
+ cookies.set({
177
+ name: this.#cookieName,
178
+ value: jwt,
179
+ httpOnly: true,
180
+ secure: true,
181
+ maxAge: this.#duration
182
+ });
183
+ }
184
+ }
185
+ missingFieldErrors(input, fields) {
186
+ const errors = [];
187
+ for (const field of fields) {
188
+ if (!input[field])
189
+ errors.push({
190
+ field,
191
+ message: "Field is required."
192
+ });
193
+ }
194
+ return errors.length > 0 ? errors : undefined;
195
+ }
196
+ async setState(cookies, { key, inputs, verb: _verb }) {
197
+ if (key === 'signout') {
198
+ await this.setBaseState(cookies, undefined);
199
+ return this.getState(cookies);
200
+ }
201
+ else if (key === 'signup') {
202
+ const errors = this.missingFieldErrors(inputs, ['username', 'password']);
203
+ if (errors) {
204
+ return { errors };
205
+ }
206
+ else if (await this.#users.has(inputs.username)) {
207
+ return { errors: [{
208
+ field: 'username',
209
+ message: 'User already exists.'
210
+ }]
211
+ };
212
+ }
213
+ else {
214
+ await this.#users.set(inputs.username, {
215
+ id: inputs.username,
216
+ password: await hash(inputs.password)
217
+ });
218
+ await this.setBaseState(cookies, inputs.username);
219
+ return this.getState(cookies);
220
+ }
221
+ }
222
+ else if (key === 'signin') {
223
+ const user = await this.#users.get(inputs.username);
224
+ if (!user) {
225
+ return { errors: [{
226
+ field: 'username',
227
+ message: `User doesn't exist.`
228
+ }]
229
+ };
230
+ }
231
+ else if (await verifyHash(inputs.password, user.password)) {
232
+ // a real authentication service will use password hashing.
233
+ // this is an in-memory just-for-testing user pool.
234
+ await this.setBaseState(cookies, inputs.username);
235
+ return this.getState(cookies);
236
+ }
237
+ else {
238
+ return { errors: [{
239
+ field: 'password',
240
+ message: "Incorrect password."
241
+ }]
242
+ };
243
+ }
244
+ }
245
+ else if (key === 'changepassword') {
246
+ const state = await this.getBaseState(cookies);
247
+ const user = await this.#users.get(state.user);
248
+ if (!user) {
249
+ return { errors: [{
250
+ field: 'username',
251
+ message: `You're not signed in as a recognized user.`
252
+ }]
253
+ };
254
+ }
255
+ else if (await verifyHash(inputs.existingPassword, user.password)) {
256
+ await this.#users.set(user.id, {
257
+ ...user,
258
+ password: await hash(inputs.newPassword)
259
+ });
260
+ return {
261
+ message: "Password updated.",
262
+ ...await this.getState(cookies)
263
+ };
264
+ }
265
+ else {
266
+ return { errors: [{
267
+ field: 'existingPassword',
268
+ message: "The provided existing password is incorrect."
269
+ }]
270
+ };
271
+ }
272
+ }
273
+ else {
274
+ return { errors: [{
275
+ message: 'Unrecognized authentication action.'
276
+ }]
277
+ };
278
+ }
279
+ }
280
+ buildApi() {
281
+ return withContext(context => ({
282
+ getState: () => this.getState(context.cookies),
283
+ setState: (options) => this.setState(context.cookies, options),
284
+ }));
285
+ }
286
+ }
@@ -0,0 +1,16 @@
1
+ import { Resource } from '../resource.js';
2
+ export declare class FileService extends Resource {
3
+ #private;
4
+ constructor(scope: Resource | string, id: string);
5
+ read(filename: string, encoding?: BufferEncoding): Promise<string>;
6
+ write(filename: string, data: string, { onlyIfNotExists }?: {
7
+ onlyIfNotExists?: boolean | undefined;
8
+ }): Promise<void>;
9
+ delete(filename: string): Promise<void>;
10
+ list({ prefix }?: {
11
+ prefix?: string | undefined;
12
+ }): AsyncGenerator<string, void, unknown>;
13
+ isAlreadyExistsError(error: {
14
+ code: any;
15
+ }): boolean;
16
+ }
@@ -0,0 +1,38 @@
1
+ import process from 'process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { Resource } from '../resource.js';
5
+ const CWD = process.cwd();
6
+ const ALREADY_EXISTS_CODE = 'EEXIST';
7
+ export class FileService extends Resource {
8
+ constructor(scope, id) {
9
+ super(scope, id);
10
+ }
11
+ #fullNameFor(filename) {
12
+ const sanitizedId = this.absoluteId.replace('~', '-').replace(/\.+/g, '.');
13
+ const sanitizedName = filename.replace('~', '-').replace(/\.+/g, '.');
14
+ return path.join(CWD, 'temp', 'wirejs-services', sanitizedId, sanitizedName);
15
+ }
16
+ async read(filename, encoding = 'utf8') {
17
+ return fs.promises.readFile(this.#fullNameFor(filename), { encoding });
18
+ }
19
+ async write(filename, data, { onlyIfNotExists = false } = {}) {
20
+ const fullname = this.#fullNameFor(filename);
21
+ const flag = onlyIfNotExists ? 'wx' : 'w';
22
+ await fs.promises.mkdir(path.dirname(fullname), { recursive: true });
23
+ return fs.promises.writeFile(fullname, data, { flag });
24
+ }
25
+ async delete(filename) {
26
+ return fs.promises.unlink(this.#fullNameFor(filename));
27
+ }
28
+ async *list({ prefix = '' } = {}) {
29
+ const all = await fs.promises.readdir(CWD, { recursive: true });
30
+ for (const name of all) {
31
+ if (prefix === undefined || name.startsWith(prefix))
32
+ yield name;
33
+ }
34
+ }
35
+ isAlreadyExistsError(error) {
36
+ return error.code === ALREADY_EXISTS_CODE;
37
+ }
38
+ }
@@ -0,0 +1 @@
1
+ export declare function prebuildApi(): Promise<void>;
@@ -0,0 +1,27 @@
1
+ import process from 'process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ export async function prebuildApi() {
5
+ const CWD = process.cwd();
6
+ let API_URL = '/api';
7
+ const indexModule = await import(path.join(CWD, 'index.js'));
8
+ try {
9
+ const backendConfigModule = await import(path.join(CWD, 'config.js'));
10
+ const backendConfig = backendConfigModule.default;
11
+ console.log("backend config found", backendConfig);
12
+ if (backendConfig.apiUrl) {
13
+ API_URL = backendConfig.apiUrl;
14
+ }
15
+ }
16
+ catch {
17
+ console.log("No backend API config found.");
18
+ }
19
+ const apiCode = Object.keys(indexModule)
20
+ .map(k => `export const ${k} = apiTree(INTERNAL_API_URL, ${JSON.stringify([k])});`)
21
+ .join('\n');
22
+ const baseClient = [
23
+ `import { apiTree } from "wirejs-resources/hosting/client.js";`,
24
+ `const INTERNAL_API_URL = ${JSON.stringify(API_URL)};`,
25
+ ].join('\n');
26
+ await fs.promises.writeFile(path.join(CWD, 'index.client.js'), [baseClient, apiCode].join('\n\n'));
27
+ }
package/package.json CHANGED
@@ -1,17 +1,27 @@
1
1
  {
2
2
  "name": "wirejs-resources",
3
- "version": "0.1.7-alpha",
3
+ "version": "0.1.9-alpha",
4
4
  "description": "Basic services and server-side resources for wirejs apps",
5
5
  "type": "module",
6
- "main": "./lib/index.js",
7
- "types": "./lib/types.ts",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
- "types": "./lib/types.ts",
11
- "default": "./lib/index.js"
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./internal": {
14
+ "types": "./dist/internal/index.d.ts",
15
+ "default": "./dist/internal/index.js"
16
+ },
17
+ "./client": {
18
+ "types": "./dist/client/index.d.ts",
19
+ "default": "./dist/client/index.js"
12
20
  }
13
21
  },
14
- "scripts": {},
22
+ "scripts": {
23
+ "build": "tsc"
24
+ },
15
25
  "repository": {
16
26
  "type": "git",
17
27
  "url": "git+https://github.com/svidgen/create-wirejs-app.git"
@@ -24,5 +34,12 @@
24
34
  "homepage": "https://github.com/svidgen/create-wirejs-app#readme",
25
35
  "dependencies": {
26
36
  "jose": "^5.9.6"
27
- }
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.7.3"
40
+ },
41
+ "files": [
42
+ "package.json",
43
+ "dist/*"
44
+ ]
28
45
  }
@@ -1,98 +0,0 @@
1
- import { CookieJar } from "./cookie-jar.js";
2
-
3
- const __requiresContext = new Symbol('__requiresContext');
4
-
5
- /**
6
- * @typedef {(...args: any) => any} ApiMethod
7
- */
8
-
9
- /**
10
- * @typedef {{
11
- * [K in string]: ApiMethod | ApiNamespace
12
- * }} ApiNamespace
13
- */
14
-
15
- /**
16
- * @template T
17
- * @typedef {T extends ((...args: infer ARGS) => infer RT)
18
- * ? ((
19
- * context: Context | boolean,
20
- * ...args: ARGS
21
- * ) => RT extends Promise<any> ? RT : Promise<RT>) : never
22
- * } ContextfulApiMethod
23
- */
24
-
25
- /**
26
- * @template T
27
- * @typedef {{
28
- * [K in keyof T]: T[K] extends ApiMethod
29
- * ? ContextfulApiMethod<T[K]>
30
- * : ContextfulApiNamespace<T[K]>
31
- * }} ContextfulApiNamespace
32
- */
33
-
34
- /**
35
- * @template {ApiNamespace | ApiMethod} T
36
- * @typedef {T extends ApiMethod
37
- * ? ContextfulApiMethod<T>
38
- * : ContextfulApiNamespace<T>
39
- * } ContextWrapped
40
- */
41
-
42
- /**
43
- * @template {ApiMethod | ApiNamespace} T
44
- * @param {(context: Context) => T} contextWrapper
45
- * @param {string[]} [path]
46
- * @returns {ContextWrapped<T>}
47
- */
48
- export function withContext(contextWrapper, path = []) {
49
- // first param needs to be a function, which enables `Proxy` to implement `apply()`.
50
- const fnOrNs = new Proxy(function() {}, {
51
- apply(_target, _thisArg, args) {
52
- const [context, ...remainingArgs] = args;
53
- let functionOrNamespaceObject = contextWrapper(context);
54
- console.log({context, args, functionOrNamespaceObject, path});
55
- for (const k of path) {
56
- functionOrNamespaceObject = functionOrNamespaceObject[k];
57
- }
58
- return functionOrNamespaceObject(...remainingArgs);
59
- },
60
- get(_target, prop) {
61
- return withContext(contextWrapper, [...path, prop])
62
- }
63
- });
64
- fnOrNs[__requiresContext] = true;
65
- return fnOrNs;
66
- }
67
-
68
- /**
69
- *
70
- * @param {Object} fnOrNS
71
- * @returns {fnOrNS is (context: Context) => T}
72
- */
73
- export function requiresContext(fnOrNS) {
74
- return fnOrNS[__requiresContext] === true;
75
- }
76
-
77
- export class Context {
78
- /**
79
- * @type {CookieJar} cookies
80
- */
81
- cookies;
82
-
83
- /**
84
- * @type {URL} location
85
- */
86
- location;
87
-
88
- /**
89
- * @param {{
90
- * cookies: CookieJar;
91
- * location: URL;
92
- * }}
93
- */
94
- constructor({ cookies, location }) {
95
- this.cookies = cookies;
96
- this.location = location;
97
- }
98
- }
@@ -1,94 +0,0 @@
1
- /**
2
- * @typedef {Object} Cookie
3
- * @property {string} name
4
- * @property {string} value
5
- * @property {number} [maxAge] - The maximum age (TTL) in seconds
6
- * @property {boolean} [httpOnly] - Whether the cookie is only accessible to the client (not JS)
7
- * @property {boolean} [secure] - Whether the cookie should only be sent over HTTPS (or localhost)
8
- */
9
-
10
- export class CookieJar {
11
- /**
12
- * @type {Record<string, Cookie>}
13
- */
14
- #cookies = {};
15
-
16
- /**
17
- * The list of cookies that have been set with `set()` which need to be
18
- * sent to the client.
19
- *
20
- * @type {Set<string>}
21
- */
22
- #setCookies = new Set();
23
-
24
- /**
25
- * Initialize
26
- *
27
- * @param {string | undefined} cookie
28
- */
29
- constructor(cookie) {
30
- this.#cookies = Object.fromEntries(
31
- (cookie || '')
32
- .split(/;/g)
33
- .map(c => {
34
- const [k, v] = c.split('=').map(p => decodeURIComponent(p.trim()));
35
- return [k, {
36
- name: k,
37
- value: v
38
- }];
39
- })
40
- );
41
- }
42
-
43
- /**
44
- * @param {Cookie} cookie
45
- */
46
- set(cookie) {
47
- this.#cookies[cookie.name] = {...cookie};
48
- this.#setCookies.add(cookie.name);
49
- }
50
-
51
- /**
52
- *
53
- * @param {string} name
54
- * @returns {Cookie | undefined}
55
- */
56
- get(name) {
57
- return this.#cookies[name] ? { ...this.#cookies[name] } : undefined;
58
- }
59
-
60
- /**
61
- *
62
- * @param {string} name
63
- */
64
- delete(name) {
65
- if (this.#cookies[name]) {
66
- this.#cookies[name].value = '-- deleted --';
67
- this.#cookies[name].maxAge = 0;
68
- this.#setCookies.add(name);
69
- }
70
- }
71
-
72
- /**
73
- * Gets a copy of all cookies.
74
- *
75
- * Changes made to this copy are not reflected
76
- *
77
- * @returns {Record<string, string>}
78
- */
79
- getAll() {
80
- const all = {};
81
- for (const cookie of Object.values(this.#cookies)) {
82
- all[cookie.name] = cookie.value;
83
- }
84
- return all;
85
- }
86
-
87
- getSetCookies() {
88
- const all = [];
89
- for (const name of this.#setCookies) {
90
- all.push({...this.#cookies[name]});
91
- }
92
- return all;
93
- }
94
- }
package/lib/resource.js DELETED
@@ -1,32 +0,0 @@
1
- export class Resource {
2
- /**
3
- * @type {Resource | string}
4
- */
5
- scope;
6
-
7
- /**
8
- * @type {string}
9
- */
10
- id;
11
-
12
- /**
13
- *
14
- * @param {Resource | string} scope
15
- * @param {string} id
16
- */
17
- constructor(scope, id) {
18
- this.scope = scope;
19
- this.id = id;
20
- }
21
-
22
- get absoluteId() {
23
- const sanitizedId = encodeURIComponent(this.id);
24
- if (typeof this.scope === 'string') {
25
- return `${encodeURIComponent(this.scope)}/${sanitizedId}`;
26
- } else if (typeof this.scope?.id === 'string') {
27
- return `${this.scope.absoluteId}/${sanitizedId}`;
28
- } else {
29
- throw new Error("Resources must defined within a scope. Provide either a namespace string or parent resource.");
30
- }
31
- }
32
- }
@@ -1,54 +0,0 @@
1
- import crypto from 'crypto';
2
- import { Resource } from '../resource.js';
3
- import { FileService } from '../services/file.js';
4
- import { overrides } from '../overrides.js';
5
-
6
- const FILENAME = 'secret';
7
-
8
- export class Secret extends Resource {
9
- /**
10
- * @type {FileService}
11
- */
12
- #fileService;
13
-
14
- /**
15
- * @type {Promise<any>}
16
- */
17
- #initPromise;
18
-
19
- /**
20
- * @param {Resource | string}
21
- * @param {string} id
22
- */
23
- constructor(scope, id) {
24
- super(scope, id);
25
- this.#fileService = new (overrides.FileService || FileService)(this, 'files');
26
- }
27
-
28
- #initialize() {
29
- this.#initPromise = this.#initPromise || this.#fileService.write(
30
- FILENAME,
31
- JSON.stringify(crypto.randomBytes(64).toString('base64url')),
32
- { onlyIfNotExists: true }
33
- ).catch(error => {
34
- if (!this.#fileService.isAlreadyExistsError(error)) throw error;
35
- });
36
- return this.#initPromise;
37
- }
38
-
39
- /**
40
- * @returns {any}
41
- */
42
- async read() {
43
- await this.#initialize();
44
- return JSON.parse(await this.#fileService.read(FILENAME));
45
- }
46
-
47
- /**
48
- * @param {any} data
49
- */
50
- async write(data) {
51
- await this.#initialize();
52
- await this.#fileService.write(FILENAME, JSON.stringify(data));
53
- }
54
- }