oficina / base Public

Clone
git clone https://amadan.net/oficina/base

Plain git — no account needed to clone.

Download

Download this file

1package store
2
3import (
4 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "crypto/subtle"
8 "database/sql"
9 "encoding/base64"
10 "encoding/hex"
11 "errors"
12 "time"
13)
14
15// A host token is what Equipo's Assistant presents when it calls Base's
16// operations for one member: "bh_" and 32 random bytes in unpadded
17// base64url. Base keeps only its SHA-256.
18const (
19 hostTokenPrefix = "bh_"
20 hostTokenBytes = 32
21)
22
23var hostTokenLen = len(hostTokenPrefix) + base64.RawURLEncoding.EncodedLen(hostTokenBytes)
24
25func hashHostToken(token string) string {
26 sum := sha256.Sum256([]byte(token))
27 return hex.EncodeToString(sum[:])
28}
29
30// MintHostToken makes a new host token for the member and returns it. It
31// replaces the member's last one, which names nobody from then on, and the
32// new one counts as not yet registered with Equipo. The token itself is
33// never stored: hand it straight to Equipo.
34func MintHostToken(ctx context.Context, db *sql.DB, memberID string) (string, error) {
35 token, err := newHostToken()
36 if err != nil {
37 return "", err
38 }
39 _, err = db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at) VALUES (?, ?, ?)
40 ON CONFLICT (member_id) DO UPDATE SET token_hash = excluded.token_hash,
41 created_at = excluded.created_at, registered_at = NULL`,
42 memberID, hashHostToken(token), time.Now().UTC())
43 if err != nil {
44 return "", err
45 }
46 return token, nil
47}
48
49// MintHostTokenFor is MintHostToken for a member whose Equipo link is
50// device dev, connected: the check and the mint are one statement, so a
51// Disconnect or a new Connect that came first leaves nothing to mint
52// (ok false), and one that comes after deletes what was minted.
53func MintHostTokenFor(ctx context.Context, db *sql.DB, memberID, dev string) (token string, ok bool, err error) {
54 if token, err = newHostToken(); err != nil {
55 return "", false, err
56 }
57 res, err := db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at)
58 SELECT ?, ?, ? WHERE EXISTS (SELECT 1 FROM equipo_links WHERE member_id = ? AND device_id = ? AND state = ?)
59 ON CONFLICT (member_id) DO UPDATE SET token_hash = excluded.token_hash,
60 created_at = excluded.created_at, registered_at = NULL`,
61 memberID, hashHostToken(token), time.Now().UTC(), memberID, dev, EquipoConnected)
62 if ok, err = affected(res, err); !ok {
63 return "", false, err
64 }
65 return token, true, nil
66}
67
68func newHostToken() (string, error) {
69 b := make([]byte, hostTokenBytes)
70 if _, err := rand.Read(b); err != nil {
71 return "", err
72 }
73 return hostTokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil
74}
75
76// MemberByHostToken is the member whose current host token is token; ok is
77// false for anything else, including the token of a member who was removed.
78func MemberByHostToken(ctx context.Context, db *sql.DB, token string) (Member, bool, error) {
79 if len(token) != hostTokenLen || token[:len(hostTokenPrefix)] != hostTokenPrefix {
80 return Member{}, false, nil
81 }
82 if b, err := base64.RawURLEncoding.Strict().DecodeString(token[len(hostTokenPrefix):]); err != nil || len(b) != hostTokenBytes {
83 return Member{}, false, nil
84 }
85 want := hashHostToken(token)
86 var stored string
87 m, err := scanMember(withFirst{db.QueryRowContext(ctx, `SELECT t.token_hash, `+memberColsOf("m")+`
88 FROM host_tokens t JOIN members m ON m.id = t.member_id WHERE t.token_hash = ?`, want), &stored})
89 if errors.Is(err, sql.ErrNoRows) {
90 return Member{}, false, nil
91 }
92 if err != nil {
93 return Member{}, false, err
94 }
95 if subtle.ConstantTimeCompare([]byte(stored), []byte(want)) != 1 {
96 return Member{}, false, nil
97 }
98 return m, true, nil
99}
100
101// withFirst scans the row's first column into first and the rest into
102// what its caller asks for.
103type withFirst struct {
104 row scanner
105 first any
106}
107
108func (w withFirst) Scan(dest ...any) error { return w.row.Scan(append([]any{w.first}, dest...)...) }
109
110// DeleteHostToken forgets the member's host token, so it names nobody.
111func DeleteHostToken(ctx context.Context, db *sql.DB, memberID string) error {
112 _, err := db.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID)
113 return err
114}
115
116// HostRegistered reports whether the member's current host token has been
117// given to Equipo. A member with no token is not registered.
118func HostRegistered(ctx context.Context, db *sql.DB, memberID string) (bool, error) {
119 var registered sql.NullTime
120 err := db.QueryRowContext(ctx, `SELECT registered_at FROM host_tokens WHERE member_id = ?`, memberID).Scan(&registered)
121 if errors.Is(err, sql.ErrNoRows) {
122 return false, nil
123 }
124 return registered.Valid, err
125}
126
127// MarkHostRegistered records that Equipo now holds the member's current
128// host token.
129func MarkHostRegistered(ctx context.Context, db *sql.DB, memberID string) error {
130 _, err := db.ExecContext(ctx, `UPDATE host_tokens SET registered_at = ? WHERE member_id = ?`, time.Now().UTC(), memberID)
131 return err
132}
133